Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 135 ยท Advanced C

C for Embedded Systems

Learn how C talks to hardware - memory-mapped registers, volatile, bit masks, fixed-width types and interrupt handlers - with runnable simulations on a PC.

An embedded system is a computer hidden inside a product: the controller in a washing machine, the firmware in a thermostat, the code in a car's window motor. These devices usually run on a microcontroller, a single chip with a small processor, a few kilobytes of RAM, some flash memory for the program, and a set of peripherals such as pins, timers and serial ports. C is the dominant language here because it maps closely to the machine, produces small and predictable code, and lets you reach any address in memory.

You can't plug a microcontroller into this website, so this lesson teaches the ideas with simulations that run on an ordinary computer: a variable plays the part of a hardware register, a function call plays the part of an interrupt. The real hardware snippets are shown in read-only blocks. You should already be comfortable with pointers, bitwise operators and bit fields.

What is different in embedded C

The language is the same, but the environment is not:

  • No operating system in many projects (called "bare metal"): your main is the first thing that runs, and it never returns.
  • Tiny memory. You may have 2 KB of RAM. Avoid recursion, large local arrays and, often, malloc altogether; fixed-size static buffers have predictable behavior.
  • Hardware is controlled through memory addresses, not function calls.
  • Events arrive asynchronously through interrupts.
  • Sizes matter. An int might be 16 bits on one chip and 32 on another, so portable code uses the fixed-width types from <stdint.h>.

Fixed-width types

Use uint8_t, uint16_t, uint32_t (unsigned) and int8_t, int16_t, int32_t (signed) whenever the exact size matters, which in hardware code is nearly always. A hardware register that is 8 bits wide should be described by a type that is 8 bits wide on every compiler. Use unsigned types for bit manipulation: shifting a negative signed value is undefined or implementation-defined behavior.

Memory-mapped registers

On most microcontrollers a peripheral is controlled by reading and writing special locations in the address space. These are called registers. Writing a bit in a "direction" register might configure a pin as an output; writing a bit in a "data" register might switch an LED on. From C's point of view, they are simply addresses:

C
#include <stdint.h>

/* Hypothetical addresses from a made-up chip's datasheet. */
#define GPIO_DIR   (*(volatile uint32_t *)0x40020000u)
#define GPIO_OUT   (*(volatile uint32_t *)0x40020004u)
#define GPIO_IN    (*(volatile uint32_t *)0x40020008u)

#define LED_PIN    5u

void led_init(void)
{
    GPIO_DIR |= (1u << LED_PIN);     /* pin 5 becomes an output */
}

void led_on(void)
{
    GPIO_OUT |= (1u << LED_PIN);
}

Read the macro from the inside out: 0x40020000u is a number; (volatile uint32_t *) reinterprets it as a pointer to a 32-bit register; the leading * dereferences it, so GPIO_DIR behaves like a variable that lives at that address. Never run this on a PC: those addresses don't exist there, and the program would crash.

Why volatile

The compiler assumes that a variable only changes when your code changes it. For a register that is wrong: a status register can change by itself when a button is pressed, and a write to an output register has a side effect even if you never read the value back. volatile tells the compiler that every access in the source must really happen, in order, and must not be cached in a CPU register or removed.

C
while ((UART_STATUS & RX_READY) == 0) {
    /* wait for a byte */
}

Without volatile on UART_STATUS, an optimizing compiler may read the register once, see that nothing in the loop changes it, and turn the loop into an infinite while (1). Note that volatile does not make an operation atomic and does not order accesses between different threads; it only prevents the compiler from optimizing the access away.

Bit masks: set, clear, toggle, test

Registers pack many one-bit flags into one word, so the core embedded skill is changing one bit without disturbing the others. There are four idioms, and each is built from a mask with exactly the target bit set (1u << n):

Goal Expression
Set bit n reg |= (1u << n)
Clear bit n reg &= ~(1u << n)
Toggle bit n reg ^= (1u << n)
Test bit n (reg >> n) & 1u or (reg & (1u << n)) != 0

Always write 1u, not 1: a plain 1 is a signed int, and 1 << 31 overflows it. Also remember the difference between reg = value (overwrites every bit) and reg |= value (read-modify-write, changes only the chosen bits).

The simulation below uses an ordinary uint8_t in place of a hardware register. The macros are the same ones you would use on real hardware.

C Set, clear, toggle and test bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Fields and named constants

Datasheets describe registers as named fields: "bits 4-6 select the clock divider". Give every field a mask and a shift, so the code says what it means:

C
#define CTRL_ENABLE_Pos   0u
#define CTRL_ENABLE_Msk   (1u << CTRL_ENABLE_Pos)
#define CTRL_DIV_Pos      4u
#define CTRL_DIV_Msk      (7u << CTRL_DIV_Pos)

uint32_t ctrl = TIMER_CTRL;                       /* read once */
ctrl &= ~CTRL_DIV_Msk;                            /* clear the field */
ctrl |= (3u << CTRL_DIV_Pos) & CTRL_DIV_Msk;      /* insert 3, never spilling out */
ctrl |= CTRL_ENABLE_Msk;
TIMER_CTRL = ctrl;                                /* write once */

Reading the register into a local, changing it there and writing it back once is both faster and safer than several separate read-modify-write operations. Prefer masks and shifts over C bit fields for hardware registers, because the bit order and padding of bit fields are implementation-defined.

Reading input pins

Hardware inputs behave differently from ordinary variables: the value can change between two reads. A typical polling loop reads a pin, waits until it is high, and later checks whether a button went from released to pressed. That last check, detecting an edge, is the core of most button handling:

C
uint8_t previous = 0;

for (;;) {
    uint8_t now = (uint8_t)((GPIO_IN >> BUTTON_PIN) & 1u);
    if (now && !previous) {
        handle_press();            /* rising edge: it just went down->up */
    }
    previous = now;
}

Real buttons also bounce, producing a burst of on/off flickers for a few milliseconds, so production code adds a short delay or counts several stable samples before accepting a press.

Interrupts

Polling wastes time. An interrupt lets the hardware pause your main code, run a short function called an interrupt service routine (ISR), and then resume exactly where it stopped. A timer can interrupt every millisecond; a serial port can interrupt when a byte arrives.

sequenceDiagram
    participant M as main loop
    participant H as hardware
    participant I as ISR
    M->>M: running normally
    H->>I: interrupt request
    Note over M,I: CPU saves state and jumps to the ISR
    I->>I: set flag, store data
    I-->>M: return from interrupt
    M->>M: sees flag and handles it

An ISR interrupts the main loop, does a tiny amount of work, and returns; the main loop does the heavy lifting afterward.

Rules for ISRs are strict, and they are the reason embedded C has its reputation for subtle bugs:

  1. Keep them short. While an ISR runs, other interrupts may be delayed. Set a flag, copy a byte into a buffer, and leave.
  2. Do not call slow or non-reentrant functions such as printf or malloc.
  3. Shared variables must be volatile. The main loop does not see the ISR in the call graph, so the compiler thinks a flag never changes unless you say otherwise.
  4. Multi-byte shared data needs protection. On an 8-bit chip, reading a 16-bit counter takes two instructions; an interrupt between them delivers a torn value. Briefly disable interrupts around the read, or use atomic types where the platform provides them.

Here is the shape of a timer ISR on a typical compiler (read-only, since the syntax for declaring ISRs differs between toolchains):

C
static volatile uint32_t ticks = 0;     /* shared between ISR and main */
static volatile uint8_t  tick_flag = 0;

void TIMER0_IRQHandler(void)            /* name comes from the chip's vector table */
{
    TIMER0_STATUS = TIMER_EVENT_CLEAR;  /* acknowledge, or it fires again at once */
    ticks++;
    tick_flag = 1;
}

int main(void)
{
    setup_timer(1000u);                 /* one interrupt per millisecond */
    enable_interrupts();

    for (;;) {
        if (tick_flag) {
            tick_flag = 0;
            blink_if_due(ticks);
        }
        sleep_until_interrupt();        /* save power */
    }
}

We can simulate this pattern on a PC by calling the "ISR" from a loop that plays the role of the hardware timer. The point of the demo is the division of labor: the handler only counts and raises a flag, and the main code does the work.

C A simulated timer interrupt

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Near, far and huge pointers (historical)

Older C tutorials, interview lists and Turbo C code mention three pointer kinds: near, far and huge. They come from the 16-bit x86 processors of the DOS era, and you will not meet them in modern compilers, but the idea behind them still explains why some embedded chips have odd pointer rules.

A 16-bit register holds only 65,536 distinct values, so a plain 16-bit address reaches just 64 KB. The 8086 reached 1 MB by combining two 16-bit numbers, a segment and an offset, into a 20-bit physical address:

TEXT
physical address = segment * 16 + offset

Compilers exposed that hardware through extra pointer keywords (the keyword spelling varied by compiler):

Kind Size Holds Reach and catch
near 2 bytes offset only, inside the current 64 KB segment Fast and small, but cannot leave the segment.
far 4 bytes segment and offset Reaches 1 MB, but the same byte has many spellings, so == and < can give wrong answers, and adding to the offset wraps at 64 KB.
huge 4 bytes segment and offset, normalized on every use Comparisons and arithmetic work across segments, at the price of slow code.

Turbo C code used them like this (read-only, because no current compiler accepts it):

C
char near *a;                 /* 2 bytes: offset in the data segment */
char far  *video = (char far *)0xB8000000L;   /* segment 0xB800, offset 0 */
char huge *big;               /* 4 bytes, safe pointer arithmetic over 1 MB */

The segment-and-offset arithmetic is easy to reproduce with ordinary integers, and it shows why far pointers are tricky: many different pairs name the same byte. This program simulates the address calculation and the normalization that huge pointers did on every operation:

C Segment:offset arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Both a and b are physical address 12345, yet comparing the fields says they differ, and the last demonstration wraps back inside the segment instead of crossing it. Those two bugs are exactly why the huge kind existed.

Why modern compilers have none. Today's 32-bit and 64-bit systems use a flat address space: one number is one byte, and every pointer is the same size (8 bytes on our runner, as the last line prints). The keywords survive only as empty macros in some headers (Windows defines near and far to nothing so old code still compiles).

What replaced them in embedded work. Small chips with separate code and data memories (a Harvard architecture) have a similar problem: a pointer into flash may not be the same kind of thing as a pointer into RAM. AVR compilers offer PROGMEM and __flash, and other toolchains use vendor qualifiers like __code or __xdata. When you read one of these programs, remember the lesson of near and far: a pointer's type may carry information about which memory it points into, so check the toolchain's documentation before casting between kinds.

Practical habits

  • Use const for read-only tables. On many chips, const data stays in flash instead of using scarce RAM.
  • Avoid floating point on small chips without a floating-point unit; it pulls in a large software library. Fixed-point integers (for example, store tenths of a degree) are cheap and exact.
  • Initialize everything. Startup code usually zeroes .bss and copies initial values into .data, but peripheral registers have their own reset values you must read in the datasheet.
  • Watch the stack. Deep call chains and big locals overflow it silently into other data.
  • Use the datasheet and vendor header. Chip makers ship a header file defining every register and field; use those names instead of typing addresses.
  • Test logic on a PC. Pure logic such as parsers, state machines and bit-twiddling code can be compiled and tested natively, as the demos here do. Only the thin layer that touches registers needs real hardware.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a pointer to a hardware status register be declared volatile?

    volatile forces every source-level access to happen. Without it, a polling loop may be turned into an infinite loop because the compiler thinks the value never changes.
  2. 2. Which expression clears bit 3 of reg and leaves other bits unchanged?

    ~(1u << 3) has every bit set except bit 3; AND-ing with it clears just that bit. The first sets the bit, the second toggles it, and the last overwrites the whole register.
  3. 3. What should an interrupt service routine usually do?

    ISRs delay other interrupts while they run and must avoid slow or non-reentrant calls. Set a volatile flag and let the main loop do the real work.
  4. 4. Why write 1u << n rather than 1 << n in register code?

    Plain 1 is a signed int. Shifting it into the sign bit is undefined (or implementation-defined in newer standards); an unsigned constant avoids the problem.
  5. 5. A 16-bit counter is updated by an ISR on an 8-bit CPU. Why can reading it in main code give a wrong value?

    Multi-byte reads are not atomic on such chips. Disable interrupts briefly around the read or copy the value in a protected section.

Summary

  • Embedded C runs on tiny, often bare-metal systems; use <stdint.h> types so sizes are the same everywhere.
  • Hardware registers are memory addresses accessed through volatile pointers, such as (*(volatile uint32_t *)0x40020000u).
  • Use unsigned masks: |= (1u << n) to set, &= ~(1u << n) to clear, ^= to toggle, (reg >> n) & 1u to test.
  • Describe multi-bit fields with a position and a mask, and read-modify-write the register once.
  • ISRs must be short, communicate through volatile shared variables, and protect multi-byte data.
  • Test pure logic natively on a PC, and keep the hardware-touching layer thin.

Next: Project: Calculator, a complete C program that ties earlier lessons together.