C programming for microcontrollers and constrained environments
Embedded Systems Programming
Write C code that runs on microcontrollers with limited RAM, no OS, and direct hardware access. This is where C truly shines.Embedded programming is like cooking in a tiny kitchen: every utensil has a fixed place, you cannot order more counter space at runtime, and if you make a mistake nobody is there to catch the falling plate. There is no operating system to catch your segfault, no debugger attached by default, and often no way to print a message. The constraints force a discipline that makes you a better programmer everywhere else.
Embedded Constraints
Limited RAM
Often 2KB-256KB total
No Heap
malloc is forbidden (non-deterministic timing, fragmentation, no recovery from failure). All memory is statically allocated at compile time.
No OS
Bare metal or RTOS
Real-time
Deterministic timing required
Memory-Mapped I/O
// Hardware registers are at fixed memory addresses.// Unlike normal variables (which live in RAM and the compiler can cache in CPU// registers), hardware registers can change value spontaneously (a button press,// a timer tick, a DMA transfer completing). The 'volatile' qualifier tells the// compiler: "read this from memory EVERY time, and write to it EVERY time --// even if you think the value hasn't changed." Without volatile, the compiler// will optimize away "redundant" reads, and your code will miss hardware events.// Example: GPIO registers for a generic ARM MCU#define GPIO_BASE 0x40020000#define GPIO_MODER (*(volatile uint32_t*)(GPIO_BASE + 0x00))#define GPIO_ODR (*(volatile uint32_t*)(GPIO_BASE + 0x14))#define GPIO_IDR (*(volatile uint32_t*)(GPIO_BASE + 0x10))#define GPIO_BSRR (*(volatile uint32_t*)(GPIO_BASE + 0x18))// Better: Use a struct for register layouttypedef struct { volatile uint32_t MODER; // Mode register volatile uint32_t OTYPER; // Output type volatile uint32_t OSPEEDR; // Speed volatile uint32_t PUPDR; // Pull-up/down volatile uint32_t IDR; // Input data volatile uint32_t ODR; // Output data volatile uint32_t BSRR; // Bit set/reset volatile uint32_t LCKR; // Lock volatile uint32_t AFR[2]; // Alternate function} GPIO_TypeDef;#define GPIOA ((GPIO_TypeDef*)0x40020000)#define GPIOB ((GPIO_TypeDef*)0x40020400)// Toggle LED on pin 5void toggle_led(void) { GPIOA->ODR ^= (1 << 5);}// Read button on pin 0bool button_pressed(void) { return (GPIOB->IDR & (1 << 0)) == 0; // Active low}
// Interrupt vector table (startup code)typedef void (*irq_handler_t)(void);extern uint32_t _estack; // From linker script__attribute__((section(".isr_vector")))const irq_handler_t vector_table[] = { (irq_handler_t)&_estack, // Initial stack pointer Reset_Handler, // Reset NMI_Handler, HardFault_Handler, MemManage_Handler, BusFault_Handler, UsageFault_Handler, 0, 0, 0, 0, // Reserved SVC_Handler, DebugMon_Handler, 0, // Reserved PendSV_Handler, SysTick_Handler, // External interrupts WWDG_IRQHandler, PVD_IRQHandler, // ... more handlers};// Interrupt handler best practicesvolatile uint32_t tick_count = 0;void SysTick_Handler(void) { tick_count++; // Keep ISRs SHORT. While this handler runs, all lower-priority // interrupts are blocked. A long ISR means missed UART bytes, delayed timer // ticks, and unpredictable system behavior. Rule of thumb: set a flag or // enqueue data, then do the real work in the main loop.}// Ring buffer for UART RX (interrupt-safe)#define RX_BUFFER_SIZE 64volatile struct { uint8_t data[RX_BUFFER_SIZE]; volatile uint8_t head; volatile uint8_t tail;} rx_buffer;void USART1_IRQHandler(void) { if (USART1->SR & USART_SR_RXNE) { uint8_t byte = USART1->DR; uint8_t next = (rx_buffer.head + 1) % RX_BUFFER_SIZE; if (next != rx_buffer.tail) { // Not full rx_buffer.data[rx_buffer.head] = byte; rx_buffer.head = next; } }}// Safe read from main loopint uart_read(void) { if (rx_buffer.head == rx_buffer.tail) { return -1; // Empty } uint8_t byte = rx_buffer.data[rx_buffer.tail]; rx_buffer.tail = (rx_buffer.tail + 1) % RX_BUFFER_SIZE; return byte;}
Critical Sections
In embedded systems without an OS, there are no mutexes. The only synchronization mechanism is disabling interrupts — which prevents any ISR from preempting your code. This is a blunt instrument: while interrupts are disabled, you miss hardware events (UART bytes, timer ticks, sensor readings). Keep critical sections as short as possible — microseconds, not milliseconds.
// Disable interrupts for critical sectionsstatic inline uint32_t disable_interrupts(void) { uint32_t primask; __asm__ volatile( "mrs %0, primask\n" // Save current interrupt state (were they already disabled?) "cpsid i\n" // Disable all interrupts : "=r"(primask) ); return primask; // Return saved state so we can restore it later}static inline void restore_interrupts(uint32_t primask) { // Restore the PREVIOUS interrupt state rather than blindly re-enabling. // This is critical: if interrupts were already disabled by a caller, // we must not re-enable them here (that would break the caller's // critical section). This pattern enables nested critical sections. __asm__ volatile("msr primask, %0" : : "r"(primask));}// Usagevoid critical_operation(void) { uint32_t state = disable_interrupts(); // Critical section - no interrupts here shared_data++; restore_interrupts(state);}// RAII-style macro (GCC extension)#define CRITICAL_SECTION \ for (uint32_t __state = disable_interrupts(), __done = 0; \ !__done; \ restore_interrupts(__state), __done = 1)void example(void) { CRITICAL_SECTION { // Protected code shared_resource = new_value; }}