Foundations · Lesson 3 of 11 · about 15 min

C for embedded

Exact-size types, bits and volatile

On a microcontroller every register has an exact size, so embedded C uses types with the size in the name.

#include <stdint.h>

uint8_t  a;   // 8 bits, 0..255       (a byte from a sensor)
uint16_t b;   // 16 bits, 0..65535    (an ADC reading)
uint32_t c;   // 32 bits              (a hardware register)
int16_t  t;   // signed 16 bits       (a temperature, can be negative)

Never use a plain int for hardware: its size changes from chip to chip.

A register is a row of switches

Each bit of a register controls one thing: a pin, a feature, a flag. The job is almost always to change one bit without touching the others. Try it here.

GoalCodeWhy it works
Turn a bit onREG |= (1 << n);OR with 1 forces it to 1
Turn a bit offREG &= ~(1 << n);AND with 0 forces it to 0
Flip a bitREG ^= (1 << n);XOR with 1 flips it
Check a bitif (REG & (1 << n))The result is not zero only if the bit is 1

volatile: read the hardware every time

The compiler removes reads it thinks are useless. The hardware changes values behind its back, so registers and variables shared with interrupts must be volatile.

volatile uint32_t *status = (volatile uint32_t *)0x40011000;
while ((*status & (1 << 5)) == 0) { }   // wait for the "data ready" bit

Interview questions

  1. How do you set, clear and toggle one bit without changing the others?
  2. What does volatile do, and when is it required?
  3. Why use uint32_t instead of int for a register?

No answers here on purpose: try answering out loud first. In the BoardPilot app, the interview coach reads your own answer and tells you what was right, what is missing and what a senior interviewer would ask next (it uses the AI provider you choose in the app). Embedded systems interview questions →

Key terms

In the app, the lessons come alive

The lessons have interactive demos and hands-on labs checked on your board in the app. These pages are the readable version: the demos are described in words, and the labs need the app.

Download BoardPilot Try the lessons in your browser