Docsity

Embedded C Programming Revision Fundementals, Summaries of Embedded Systems Programming

Toggle sidebar
bg1
Embedded C · Lab 1 Revision Page 1 of 7
Embedded C Programming
Lab 1 — Revision Notes
Simplified study notes · Data types · Operators · Control flow · Bit manipulation · Enums & FSM · Qualifiers ·
Functions
1Variables & Data Types
What is a variable?
Avariable is a named place in RAM that stores a value which can change while the program runs. Its data
type decides two things: how many bytes it gets, and how the bits are interpreted.
Primitive data types
Type Size Format Holds Example
char 1 byte %c one character 'A'
int 4 bytes %d whole numbers 60
float 4 bytes %f decimals (single precision) 36.6f
double 8 bytes %lf decimals (double precision) 3.1415926535
char grade = 'A';
int speed = 60;
float temp = 36.6f;
double pi = 3.1415926535;
printf("%c\n", grade);
printf("%d\n", speed);
printf("%f\n", temp);
printf("%lf\n", pi);
Output
A
60
36.599998
3.141593
•%f /%lf print 6 decimal places by default, so pi shows as 3.141593.
•36.599998: a float cannot store every decimal exactly, so 36.6 is saved as the nearest binary value.
Extra tip
Sizes depend on the CPU architecture (
int
can be 2 bytes on 8/16-bit microcontrollers). In embedded
code, prefer fixed-size types from <stdint.h> such as uint8_t and int32_t.
pf3
pf4
pf5

Partial preview of the text

Download Embedded C Programming Revision Fundementals and more Summaries Embedded Systems Programming in PDF only on Docsity!

Embedded C Programming

Lab 1 — Revision Notes

Simplified study notes · Data types · Operators · Control flow · Bit manipulation · Enums & FSM · Qualifiers · Functions

1 Variables & Data Types

What is a variable?

A variable is a named place in RAM that stores a value which can change while the program runs. Its data type decides two things: how many bytes it gets, and how the bits are interpreted.

Primitive data types

Type Size Format Holds Example char 1 byte %c one character 'A' int 4 bytes %d whole numbers 60 float 4 bytes %f decimals (single precision) 36.6f double 8 bytes %lf decimals (double precision) 3.

char grade = 'A'; int speed = 60; float temp = 36.6f; double pi = 3.1415926535;

printf("%c\n", grade); printf("%d\n", speed); printf("%f\n", temp); printf("%lf\n", pi);

Output

A 60

  • %f / %lf print 6 decimal places by default, so pi shows as 3.141593.
  • 36.599998: a float cannot store every decimal exactly, so 36.6 is saved as the nearest binary value.

Extra tip

Sizes depend on the CPU architecture (int can be 2 bytes on 8/16-bit microcontrollers). In embedded

code, prefer fixed-size types from such as uint8_t and int32_t.

Signed vs unsigned

Signed Unsigned Top bit (MSB) used as the sign bit used as part of the value Range for n bits − 2 n−^1 to 2 n−^1 − 1 0 to 2 n^ − 1 Example with 8 bits −128 to 127 0 to 255

Overflow

When a result is bigger than the type can hold, overflow happens. For unsigned types the value wraps

around (modulo 2 N^ , where N is the number of bits).

unsigned char count = 250; count = count + 10; // 260 does not fit -> wraps around -> count = 4

Correction to the original note

The result 4 is right, but the maths was written as 260 mod 255 , which equals 5. The modulus is

28 = 256, not 255: 260 mod 256 = 4.

Extra tip Overflow of signed integers is undefined behaviour in C, so avoid it.

2 Constants & Operators

Constants: const vs #define

A constant is a value that cannot change after it is created.

const #define Handled by the compiler the preprocessor What it does real variable, read-only pure text replacement Type checking yes no Scope rules obeys scope none When during compilation before compilation

const int MAX_SPEED = 120; // typed, scoped, checked by the compiler #define LED_PIN 5 // replaced by the text "5" before compiling

Arithmetic & relational operators

  • Arithmetic: + - * / %
  • Relational: == != < > <= >= give 1 (true) or 0 (false).
  • Integer division throws away the fraction; % gives the remainder.

for ( int i = 0; i < 5; i++) { if (i == 2) continue ; // skip 2 if (i == 4) break ; // stop the loop at 4 printf("%d ", i); }

Output

4 Bit Manipulation

The mask idea

1U << n builds a mask with a single 1 at position n. Combine the register (REG) with this mask using

|, & or ^ to change only that bit and leave every other bit untouched.

Single-bit cheat sheet

Goal Code Why it works Set bit n REG |= (1U << n); OR with 1 forces the bit to 1 Clear bit n REG &= ~(1U << n); inverted mask has 0 only at n, so AND clears it Toggle bit n REG ^= (1U << n); XOR with 1 flips the bit; XOR with 0 changes nothing Test bit n if (REG & (1U << n)) AND isolates that bit; non-zero means it is set

Example with an 8-bit register, REG = 0000 1010:

Operation Result Explanation Set bit 2 0000 1110 bit 2 becomes 1 Clear bit 3 0000 0010 bit 3 becomes 0 Toggle bit 1 0000 1000 bit 1 flips from 1 to 0

Bit fields (several bits together)

Extract a field: shift it down to bit 0, then mask its width. Modify a field: use a read-modify-write cycle.

1. Clear the field with an inverted, shifted mask. 2. OR the new value in, shifted to the field position.

// Extract val = (REG >> Shift) & Mask;

// Modify (read-modify-write) REG = (REG & ~(Mask << Shift)) | ((Val & Mask) << Shift);

// Example: 3-bit field at offset 4 -> Mask = 0x7, Shift = 4

5 Enumerations & State Machines

Enumerations

An enum gives names to integer constants, which removes “magic numbers” and makes the code readable.

Values start at 0 and go up by 1 unless you set them.

typedef enum { SYS_IDLE = 0, SYS_RUNNING = 1, SYS_ERROR = 2 } SystemState_t;

Finite State Machine (FSM)

An FSM moves between explicit states when an input event happens. A state transition table lists, for every current state and input, the next state.

Example: a 2-state toggle controlled by a button.

Current state Button pressed? Next state OFF no OFF OFF yes ON ON no ON ON yes OFF

FSM in C: enum + switch

typedef enum { STATE_OFF, STATE_ON } State_t;

void process_button_press(State_t *state, int btn_pressed) { if (!btn_pressed) return ; // no press -> stay in current state

switch (*state) { case STATE_OFF: *state = STATE_ON; break ; case STATE_ON: *state = STATE_OFF; break ; } }

6 Qualifiers & Storage

const qualifier

Marks a variable as read-only. This allows the compiler to keep the data in ROM/Flash instead of RAM, which saves precious RAM.

int add( int a, int b); // declaration int add( int a, int b) { return a + b; } // definition

Pass-by-value vs pass-by-pointer

C always passes by value : the function gets a copy of each argument, so changing the copy never changes the caller’s variable. To modify the original, pass its address (a pointer) and dereference it.

void change_copy( int x) { x = 99; } // changes only the copy void change_orig( int *x) { *x = 99; } // changes the caller's variable

int n = 5; change_copy(n); // n is still 5 change_orig(&n); // n is now 99

Why recursion is risky in embedded C

A recursive function calls itself until it reaches a base case. Every call adds a stack frame to the microcontroller’s small RAM stack, so deep or endless recursion causes a stack overflow.

Watch out Recursion is restricted or banned in safety-critical embedded code (for example MISRA C ). Use a loop instead.

8 Quick Recap

  • Unsigned overflow wraps around (modulo 2 N^ ).
  • #define = text replacement; const = typed read-only variable.
  • ++a: change first, then use. a++: use first, then change.
  • switch accepts only int, char and enum.
  • Set |= · Clear &= ~ · Toggle ^= · Test &
  • Change a bit field with read-modify-write.
  • volatile = always re-read from memory; static = keeps its value / hides it from other files.
  • C passes by value: use a pointer to modify the caller’s variable.
  • Avoid recursion in embedded systems: the stack is tiny.