š” Memory, pointers and volatile
-
Desktop C forgives you. Firmware C doesn't. The same program that runs fine on a laptop can corrupt memory or miss an interrupt on a microcontroller ā because of what the compiler and the hardware actually do with your code.
The bugs that keep showing up here
The missing
volatile. A flag shared between main code and an interrupt handler works perfectly at -O0 and breaks at -O2, because the compiler cached it in a register. It never re-read memory ā you never told it the value could change behind its back. The canonical shape looks like this:volatile bool data_ready = false; // set in ISR, polled in main loop void ADC_ISR(void) { data_ready = true; } void loop(void) { if (data_ready) { // re-read from memory every time data_ready = false; process_sample(); } }Drop the
volatileand the compiler hoists the read out of the loop ā the loop never sees the interrupt fire. Diagnosing it: if it works at -O0 but breaks at -O2, suspect a missing qualifier before suspecting hardware. Any variable touched both inside and outside an ISR getsvolatile. No exceptions, no "but it works on my machine".
ā Interrupts and ISR patternsStructs that don't match the hardware. You overlay a struct on a peripheral register map, but the compiler inserts padding where you didn't expect it, and now every field after the gap writes to the wrong address. On desktop this is a curiosity; on hardware it configures a peripheral into nonsense. Learn struct layout and padding, then verify with
sizeofandoffsetofinstead of trusting the layout.
ā Memory, pointers and data representationRead-modify-write that isn't atomic.
GPIO_REG |= (1 << PIN)looks harmless until an interrupt fires between the read and the write and modifies a neighbouring pin ā your write-back silently undoes it. On real firmware this shows up as a pin that "randomly" changes state once a week. Critical regions and atomic access exist for exactly this reason. Integer promotion adds a second trap: youruint8_tarithmetic quietly becomesintmid-expression, signed-vs-unsigned comparisons go sideways, and shifting into the sign bit is undefined behaviour the compiler is allowed to punish.
ā Writing robust embedded C
Start at the Embedded C track and work through it in order. Post the smallest reproducer plus your compiler flags and optimisation level. Tag with
c-lang.
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better š
Register Login