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

One page of what you use most. Press the button, then choose "Save as PDF" in the print window.

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 -> restoreA critical section, protecting a short read-modify-write from an ISR race.
xTaskCreate / vTaskDelay / xQueueSendRepresentative FreeRTOS-style API names for tasks, delays and queues.

Reliability and safety

pet the watchdog only when genuinely healthyNever pet unconditionally from a free-running timer ISR.
CRC-check a firmware image before booting itCatches accidental corruption; secure boot adds authenticity on top.
always explicitly initialize every variableAvoids 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-whileThe 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) >> shiftExtract a multi-bit field: mask it out, then shift down to start at bit 0.