Skip to content

C Programming Tips & Tricks

2 Topics 2 Posts

Patterns, idioms, common bugs, best practices in C for embedded

This category can be followed from the open social web via the handle c-programming-tips-tricks@forum.grapesiot.com

  • šŸ”§ Bits, registers and clean HALs

    c-lang embedded-c hal
    1
    0 Votes
    1 Posts
    102 Views
    A
    Hardware speaks in bits, and C is how you answer. Nearly every peripheral bring-up is the same loop: read the register map row, build the mask, write it, read it back to verify. Engineers who are fluent in that loop bring up drivers in an afternoon; everyone else spends a week toggling the wrong bit. The core skills Bit manipulation as a first language. Setting, clearing, toggling and testing individual bits with shifts and masks — REG |= (1 << EN), REG &= ~(3 << MODE), if (REG & READY) — is the vocabulary of every driver you'll ever write. Practice until masks feel like plain reading. → Bit manipulation and register programming → Hands-on bit manipulation exercises Structs as register maps and sensor data. A well-laid-out struct overlays a peripheral's registers or packs a sensor reading (SensorReading_t with temperature, humidity, timestamp) into something every layer of firmware can share. Unions pull double duty for protocol payloads where the same bytes mean different things by message type. → Functions, structs, unions and macros Functions, macros and the HAL habit. Raw register writes scattered through application code rot fast. A thin hardware-abstraction layer — sensor_init(), sensor_read(), one place per peripheral — means a pin change or a sensor swap touches one file, not forty. Know when a macro beats a function (and when it hides a double-evaluation bug). Headers and sources that scale. One giant main.c dies at a few hundred lines. Split by peripheral and by concern, guard every header, keep ISRs thin and fast, and let the build tell you about mistakes with warnings-as-errors before the hardware does. Start at the Embedded C deep track for the full six-part treatment. Share a driver snippet, a mask trick, or a HAL layout that survived contact with real hardware. Tag with c-lang.
  • šŸ’” Memory, pointers and volatile

    c-lang embedded-c firmware
    1
    0 Votes
    1 Posts
    84 Views
    A
    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 volatile and 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 gets volatile. No exceptions, no "but it works on my machine". → Interrupts and ISR patterns Structs 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 sizeof and offsetof instead of trusting the layout. → Memory, pointers and data representation Read-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: your uint8_t arithmetic quietly becomes int mid-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.