Home / Learn Embedded C / Cheat Sheet
Cheat Sheet
One printable page of the patterns and snippets used most throughout this course.
In shortOne printable page of the patterns and snippets used most throughout this course.
What's actually going on
In plain terms
A condensed, one-page reference of the bitwise patterns, GPIO calls, interrupt/RTOS reminders and safety practices used repeatedly throughout this course, meant to be printed or saved for quick lookup.
Why we use it
Having the most-used patterns in one place saves time re-deriving or re-finding them while actually writing embedded code, especially early on before they become second nature.
Under the hood
Use the print button to save this page as a PDF for offline reference, or just bookmark it for quick lookup while working.
Real-world use
- Quick reference
- Printable summary
- Daily lookup
GPIO and timing
pinMode(pin, OUTPUT/INPUT); | Set a pin's direction before using it. |
GPIO_WRITE(pin, HIGH/LOW); | Drive an output pin's level. |
GPIO_READ(pin); | Read an input pin's current level. |
PWM_WRITE(pin, duty_0_to_255); | Set a PWM output's duty cycle. |
Interrupts and RTOS
volatile int flag; (real C, not this sandbox) | Required for any variable shared between an ISR and main-loop code. |
disable interrupts -> critical work -> restore | A critical section, protecting a short read-modify-write from an ISR race. |
xTaskCreate / vTaskDelay / xQueueSend | Representative FreeRTOS-style API names for tasks, delays and queues. |
Reliability and safety
pet the watchdog only when genuinely healthy | Never pet unconditionally from a free-running timer ISR. |
CRC-check a firmware image before booting it | Catches accidental corruption; secure boot adds authenticity on top. |
always explicitly initialize every variable | Avoids undefined/garbage values, especially important in this course's sandbox. |
C basics
const int NAME = value; | A typed, debuggable named constant (safer than #define in this course's sandbox and in general style). |
for / while / do-while | The three loop forms; do-while always runs its body at least once. |
static int x; (inside a function) | A local variable that keeps its value between calls. |
sizeof(arr) / sizeof(arr[0]) | The portable way to compute an array's element count. |
Registers and bit ops
reg |= (1 << N); | Set bit N, leaving every other bit unchanged. |
reg &= ~(1 << N); | Clear bit N, leaving every other bit unchanged. |
reg ^= (1 << N); | Toggle bit N (flip it to its opposite state). |
if (reg & (1 << N)) | Check whether bit N is set (always parenthesize the AND). |
(reg & mask) >> shift | Extract a multi-bit field: mask it out, then shift down to start at bit 0. |