unfried.
Streak:0 days XP:0

Firmware reference

Firmware

Bit operations, register idioms, timer and serial arithmetic, and the RTOS rules.

72 entries in 12 units. Free to use and share.

Jump to a unit (12 units)

Unit 1 Bits that move pins

Bit n is pin n

In GPIOA->ODR (outputs) and GPIOA->IDR (inputs), bit n is pin PAn, counting from 0 at the right. On a Nucleo-F072RB the green LED LD2 is on PA5.

Taught in A pin is a bit in a register

Hex to binary

One hex digit is 4 bits; convert each digit on its own with weights 8, 4, 2, 1. Single-bit masks are 0x01, 0x02, 0x04, 0x08, then 0x10 to 0x80; each zero digit on the right moves 4 bits up, so 0x0100 is bit 8.

Taught in Hex and binary fluency

Set, clear, toggle

Each leaves every other bit alone.

REG |= 1u << n;      // set bit n
REG &= ~(1u << n);   // clear bit n
REG ^= 1u << n;      // toggle bit n

Careful: REG = 1u << n; writes every bit: pin n high, all others low. Bracket the ~: ~1u << 7 clears bits 7 to 0.

Taught in Setting a bit without breaking the others

Testing an input bit

if (REG & (1u << n)) { /* bit n is 1 */ }

Careful: The masked value is 0 or 1u << n (4 for bit 2), so never compare it with 1.

Taught in Testing an input bit

Writing a 2-bit field

Pin n owns MODER bits 2n+1 and 2n; 00 input, 01 output, 10 alternate function, 11 analog. OR can't clear bits, so clear the field first.

GPIOA->MODER = (GPIOA->MODER & ~(3u << (2u * n))) | (1u << (2u * n));

Careful: GPIOA's MODER resets to 0x28000000; PA13 and PA14 are the SWD pins, and overwriting them disconnects the debugger.

Taught in Multi-bit fields

Unit 2 C for embedded

Fixed-width integers

Unsigned results wrap mod 2N⁠; uint8_t 250 + 10 is 4. A signed type's top bit counts negative, so 1111 1111 in an int8_t is −1.

TypeRange
uint8_t0 to 255
int8_t−128 to 127
uint16_t0 to 65,535
int16_t−32,768 to 32,767
uint32_t0 to 4,294,967,295
int32_t−2,147,483,648 to 2,147,483,647

Taught in Fixed-width integers

Integer promotion and undefined behavior

Before arithmetic, comparison or ~, anything narrower than int becomes int, so ~(uint8_t)0x0F is 0xFFFFFFF0. Signed overflow is undefined, so write 1u << 31, not 1 << 31. == binds tighter than &; write (IDR & mask) == 0.

Taught in Loops that never end

Where variables live

RAM use is data + bss in arm-none-eabi-size.

DeclarationLives inSet up by
const globalflashthe programmer
global or static, nonzero startRAM, .datastartup copies from flash
global or static, zero startRAM, .bssstartup zeroes it
plain localstacknobody; starts as leftovers

Taught in Where variables live

Reset sequence

The CPU loads SP from vector-table word 0 and PC from word 1 (Reset_Handler, bit 0 set for Thumb). Reset_Handler copies .data, zeroes .bss, calls SystemInit() and then main(). Entry n is at 0x0800_0000 + 4n; interrupt k is entry 16 + k.

Taught in Before main()

Memory-mapped registers

GPIO offsets are MODER 0x00, PUPDR 0x0C, IDR 0x10, ODR 0x14, BSRR 0x18; GPIOA is at 0x4800_0000.

*(volatile uint32_t *)0x48000014 = 0x20;   // GPIOA ODR: PA5 high
GPIOA->ODR = 0x20;                         // the same, in CMSIS

Taught in Pointers and memory-mapped registers

volatile

Every read and write happens, in program order. Use it for flags an ISR sets and for anything that reaches hardware.

Careful: volatile is not atomic; x++ is load, add, store. Guard updates with __disable_irq() / __enable_irq().

Taught in volatile

Unit 3 GPIO in practice

Push-pull and open-drain

Two push-pull outputs that disagree fight (about 66 mA, the wire near 1.65 V). Open-drain only pulls low; a pull-up brings the wire high, so several drivers can share it. One driver, push-pull; several, open-drain plus one pull-up.

Taught in Push-pull and open-drain

Driving an LED

Pin → resistor → LED → ground sources, active-high. 3.3 V → resistor → LED → pin sinks, active-low. Count the pin's 25 Ω in the loop. For an active-low load, write the off level to ODR before switching MODER to output.

Taught in Driving an LED: source or sink

Inputs and pulls

An unconnected input floats. Button to ground needs a pull-up and reads 0 pressed. PUPDR is 00 none, 01 pull-up, 10 pull-down; the internal pull-up is 25–55 kΩ.

GPIOB->PUPDR = (GPIOB->PUPDR & ~(3u << 4)) | (1u << 4);   // PB2 pull-up

Taught in Reading inputs: pull-ups and floating pins

Edge detection

if (now && !was) presses++;
was = now;   // every pass, after the test

Careful: A press shorter than the sample period can be missed.

Taught in Polling and edge detection

Software debounce

Take a sample every T from a timer; switch state only when N samples in a row disagree with it. N×T must outlast the bounce (up to 6.2 ms for most switches). Worst delay is bounce + N×T⁠.

Careful: Never time T with a counted loop.

Taught in Debouncing in software

Enable the clock first

Unclocked ports ignore writes and read 0. GPIOBEN is bit 18, GPIOCEN 19.

RCC->AHBENR |= RCC_AHBENR_GPIOAEN;   // bit 17
(void)RCC->AHBENR;                   // read back
/* then MODER, OTYPER, PUPDR */

Taught in Enable the clock first

Unit 4 Timers and PWM

Timer update rate

fupdate
update rateHz
fclk
timer clockHz
PSC
prescaler registerno unit
ARR
auto-reload registerno unit

Applies: Registers hold N − 1. 48 MHz, PSC = 47, ARR = 999 gives 1 kHz. A new PSC loads at the next update, or at once with EGR = TIM_EGR_UG.

Taught in Counting clock ticks

Why not a delay loop

A counted loop takes cycles, not microseconds. -O2 can delete it, a faster clock shortens it, and every interrupt stretches it. A timer counts in hardware.

Taught in Why not a delay loop

PWM duty

CCR1
compare registerno unit
ARR
auto-reload registerno unit

Applies: PWM mode 1 (OC1M = 110); the pin is high while CNT < CCR1. CCR1 > ARR is 100 %. ARR + 1 is the number of duty steps.

Careful: Change ARR and you must rescale CCR1.

Taught in PWM: duty and frequency

PWM and what eyes see

Brightness looks roughly like duty^(1/2.2); to look like level L of 255, use duty = (L/255)^2.2 from a table. Above about 100 Hz a still eye sees steady light; 1 kHz or more keeps moving eyes and cameras from catching it.

Taught in PWM and what eyes see

Input capture period

On each edge the timer copies CNT into CCR1. The difference in the counter's width survives one wrap, so the period must be under 65,536 counts.

uint16_t period = (uint16_t)(c2 - c1);   // 16-bit timer

Taught in Input capture

Wrap-safe time

A 32-bit ms tick wraps after 49.7 days. Compare differences, never times.

if (now - start >= period)              // elapsed: up to 2^32 − 1 ms
if ((int32_t)(now - deadline) >= 0)     // deadline: up to 24.8 days ahead

Careful: if (now > deadline) fails near the wrap.

Taught in Tick counters and wraparound

Unit 5 Interrupts

Polling latency

A polled input is seen once per pass; worst-case response is the longest pass, every delay_ms() included. A busy wait stalls the whole loop.

Taught in Polling vs interrupts

EXTI bring-up for a button

RCC->APB2ENR |= RCC_APB2ENR_SYSCFGCOMPEN;
SYSCFG->EXTICR[3] = (SYSCFG->EXTICR[3] & ~0xF0u) | 0x20u;  // line 13 = PC13
EXTI->FTSR |= 1u << 13;                                    // falling edge
EXTI->IMR  |= 1u << 13;                                    // unmask
NVIC_SetPriority(EXTI4_15_IRQn, 2);
NVIC_EnableIRQ(EXTI4_15_IRQn);

Careful: Route the line before you unmask it; at reset every line watches port A.

Taught in Enable, handle, clear

Clear the pending flag first

FlagCleared byWrite
EXTI->PR bit nwriting 1EXTI->PR = 1u << n;
TIM3->SR UIFwriting 0TIM3->SR = ~TIM_SR_UIF;
USART RXNEreading RDRb = USART2->RDR;

Careful: Never |= a write-1-to-clear register; it clears other lines' flags. A flag left set re-enters the ISR forever.

Taught in Enable, handle, clear

Critical section

For read-modify-writes and values that change together. Keep it a few instructions long. If interrupts may already be off, save and restore PRIMASK instead.

__disable_irq();
uint32_t c = count;
count = 0;
__enable_irq();

Taught in Sharing data with an ISR

Atomic pin writes with BSRR

GPIOA->BSRR = 1u << n;          // set pin n
GPIOA->BSRR = 1u << (n + 16);   // reset pin n

Careful: GPIOA->ODR |= bit is a read-modify-write.

Taught in Sharing data with an ISR

Keep ISRs short

Clear the flag, copy the data, set a flag or bump a count, return. No waits, no blocking UART, no printf or malloc; only FromISR calls in FreeRTOS. A pending flag holds one request, so slow ISRs lose events.

Taught in Keep ISRs short

Priorities and worst-case latency

On the NVIC a smaller number is more urgent (the F072 has levels 0 to 3); FreeRTOS task priorities count the other way. Worst latency = the longest ISR at its own level + each more urgent ISR that can fire + interrupts-off time + entry time.

Taught in Priorities and nesting

Unit 6 UART

UART frame (8N1)

Idle high; start bit 0, 8 data bits LSB first, stop bit 1. That is 10 bits per byte.

BaudOne bitOne byteBytes/s, max
9600104 µs1.04 ms960
1152008.68 µs86.8 µs11,520
1,000,0001 µs10 µs100,000

Careful: Dividing the baud by 8 forgets the start and stop bits.

Taught in Framing: start, data, stop

Baud register

BRR
USART baud register, rounded to a whole numberno unit
fclk
USART clockHz

Applies: 16× oversampling. 48 MHz at 115200 gives 417, −0.08 %.

Careful: BRR = 417 on a chip still at its 8 MHz reset clock gives 19,185 baud and clean-looking garbage.

Taught in Baud error

Baud tolerance

The stop-bit sample sits 9.5 bit times after the start edge and must drift less than half a bit, so the ideal total mismatch for both ends is under 0.5/9.5=5.3 %⁠. Real receivers allow about 3.3–4.4 %; budget under ±2 % per end.

Taught in Baud error

Ring buffer

The ISR writes head, main writes tail, no shared count. Size it for main's longest gap plus one free slot, rounded up to a power of two.

uint32_t next = (rx_head + 1u) & (RX_N - 1u);
if (next != rx_tail) { rx_buf[rx_head] = b; rx_head = next; }

Careful: & (N − 1) only wraps correctly when N is a power of two.

Taught in Ring buffers

Logging without wrecking timing

A blocking print waits 86.8 µs per character at 115200. A TX ring fed by the TXE interrupt removes the wait, not the bandwidth limit; keep logged bytes per second well under the link's figure, and drop and count when full.

Taught in Logging without wrecking timing

Parsing lines

End a line on CR or LF, skip empty lines, cap the length, and drop an overlong line up to the next line end. An XOR checksum catches any single flipped bit but misses the same bit flipped in two bytes and reordered bytes.

Taught in Parsing lines and frames

Unit 7 SPI and I²C

SPI register read

Each SCK clock moves one bit each way, so to receive N bytes the master sends N.

GPIOB->BRR = 1u << 6;          // CS low
spi_xfer(0x80 | 0x0F);         // command; the return is junk
uint8_t id = spi_xfer(0x00);   // dummy brings the value back
GPIOB->BSRR = 1u << 6;         // CS high

Taught in SPI: the master makes every clock

SPI modes

Mode = 2 × CPOL + CPHA. A wrong mode shifts every byte by one bit.

ModeCPOL, CPHASCK idlesSamples on
00, 0lowrising
10, 1lowfalling
21, 0highfalling
31, 1highrising

Careful: Slowing SCK doesn't fix a wrong mode.

Taught in SPI modes

I²C address byte

First byte is (7-bit address << 1) | R/W, with 0 = write, 1 = read; 0x76 becomes 0xEC and 0xED. The receiver ACKs on the 9th clock; in a read the master NACKs the last byte, then sends STOP.

Careful: Sending the datasheet's 0x76 as the byte calls address 0x3B.

Taught in I²C: open-drain, addresses, ACK

Reading a sensor register

START, address + write, register, repeated START (no STOP), address + read, data, NACK, STOP. A register write needs one START.

Taught in Reading a sensor register

I²C pull-up rise time

tr
rise time, 30 % to 70 %s
R
pull-upΩ
C
bus capacitanceF

Applies: At most 1000 ns at 100 kHz, 300 ns at 400 kHz. The low end is R≥(3.3 V−0.4 V)/3 mA=967 Ω⁠.

Taught in I²C: open-drain, addresses, ACK

Clearing a stuck bus

A reset mid-read can leave a sensor holding SDA low. At boot, if SDA is low, drive SCL as an open-drain GPIO for up to 9 pulses until SDA rises, then send a STOP and check SDA again. If that never frees it, cut the sensor's power.

Taught in When the bus hangs

Unit 8 Memory and DMA

Sizing a stack

Add the deepest chain of frames live at once, an interrupt on top (32 B stacked by the core plus the handler's frame), then about 25 % margin. A big local array lives in the frame on every call.

Careful: On the F072 nothing checks overflow; the bug shows up later, wherever the damaged data is used.

Taught in The stack and how it overflows

Heap fragmentation

malloc(n) needs one gap of at least n bytes plus a header; the largest free block, not the total, says what succeeds. heap_4 adds an 8-byte header and rounds to 8, so malloc(20) takes 32 B. Prefer static arrays, fixed-size pools, or one malloc at boot.

Careful: No malloc in an ISR. Always check for NULL.

Taught in The heap and fragmentation

Per-sample interrupt cost

CPU load is sample rate × ISR time; 100,000 × 2 µs is 20 % of the CPU before main does anything. DMA with one interrupt per buffer cuts it to a fraction of a percent.

Taught in DMA: moving data without the CPU

DMA setup rules

CNDTR counts transfers, not bytes (64 for uint16_t buf[64]). CPAR, CMAR and CNDTR can only be written while EN is 0; set EN last. Without DMACFG the ADC stops requesting after one buffer.

Taught in DMA: moving data without the CPU

Circular double buffer

N
buffer length, samplesno unit
f
sample rateHz
P
processing time per halfs
d
start-up delays
L
latency limit on a half's fill times

Applies: Circular DMA with HTIE and TCIE; process each half while the DMA fills the other.

Careful: Processing the whole buffer at transfer complete races the DMA.

Taught in Circular and double buffers

Caches and DMA (Cortex-M7)

Before a DMA send, clean the buffer; after a DMA receive, invalidate it before the CPU reads. Align buffers to 32 bytes and size them in multiples of 32. volatile doesn't bypass the cache.

Careful: Never invalidate a buffer the CPU has written and not cleaned.

Taught in Caches and DMA

Unit 9 Program structure and state machines

Superloop latency

A blocking call stops every other line of the loop. A polled input is sure to be seen only if it lasts one pass; worst response is one pass. A UART read once per pass gets at most one byte per pass.

Taught in The superloop and blocking delays

Non-blocking timing

Worst latency becomes the longest pass, the work of every job that can come due together.

if (ms_ticks - last >= 500u) {   // elapsed form, wrap-safe
    last += 500u;                // += keeps the beat
    GPIOA->ODR ^= 1u << 5;
}

Careful: last = ms_ticks drifts; ms_ticks == t or % period == 0 can be skipped or fire many times.

Taught in Non-blocking timing

Explicit state machines

N booleans hold 2N combinations, most of them impossible states. Use one enum and a switch with no default:, so gcc -Wall warns about unhandled states. A missing break falls through; -Wextra warns.

Taught in Explicit state machines

Transition tables

One row per state, one column per event, each cell a next state and an action. Put STAY at 0 so unlisted cells are harmless. Timeouts are events: store t0 on entry and send EV_TIMEOUT when ms_ticks - t0 >= limit.

Taught in Events and transition tables

Layers you can test

Driver (one per chip), HAL header, application calling only the HAL. Build the application on a laptop with fake HAL functions to test logic. Register setup, clocks and latency still need the board.

Taught in Layers you can test

Unit 10 RTOS: tasks and scheduling

Tasks block, loops spin

vTaskDelay(), a blocking xQueueReceive and ulTaskNotifyTake() leave the CPU. delay_ms() and while (!flag) keep it, so every lower task waits. The kernel always runs the highest-priority ready task.

Taught in Why tasks

Preemption

A switch happens inside the call that readies a more urgent task, not at the next tick. Delays end in a tick interrupt. Equal priorities take turns, one tick each. Priority sets the order, not the speed.

Taught in Preemption

vTaskDelayUntil for fixed periods

TickType_t last = xTaskGetTickCount();   // once
for (;;) {
    sample_and_filter();
    vTaskDelayUntil(&last, pdMS_TO_TICKS(10));
}

Careful: vTaskDelay(n) counts from the call, so the period is work + preemption + n and the error adds up.

Taught in vTaskDelay vs vTaskDelayUntil

Queues copy

xQueueSend(q, &x, timeout) copies the bytes of x in; afterwards x is yours again. A queue of pointers copies only the pointer, so never send a pointer to a local. Timeout 0 on a full queue returns errQUEUE_FULL at once.

Taught in Queues copy

From ISR to task

Only FromISR calls in an ISR. Without the yield, the woken task waits up to a tick.

BaseType_t woken = pdFALSE;
xQueueSendFromISR(rx_q, &b, &woken);
portYIELD_FROM_ISR(woken);

Taught in From ISR to task

Utilization and rate-monotonic order

Utilization is the sum of each task's run time over its period; 0.2/1 + 3/10 + 20/100 = 0.70. Rate-monotonic order gives the shortest period the highest priority.

Careful: Enough CPU in total doesn't mean every deadline is met; order matters.

Taught in Checkpoint: Tasks and scheduling

Unit 11 RTOS: sharing safely

Race conditions

counter++ is load, add, store; a switch in between loses an update. One aligned 32-bit load or store and a BSRR write are atomic. x++, flags |= BIT, ODR |= bit, a uint64_t or a struct are not.

Taught in Race conditions

Critical sections in FreeRTOS

On the M0 it masks every interrupt, SysTick too. A masked stretch of T loses UART bytes and ticks, and adds T to every ISR's latency.

taskENTER_CRITICAL();
struct reading r = latest;   // copy, a few instructions
taskEXIT_CRITICAL();
lcd_show_reading(&r);        // slow part outside

Careful: Never block inside.

Taught in Critical sections

Mutex or semaphore

A task notification signals one named task.

PropertyMutexBinary semaphore
Startsfreeempty
Ownerthe task that took itnone
Priority inheritancealwaysnever
From an ISRnot allowedxSemaphoreGiveFromISR()
Use forguarding a resourcea signal any task may take

Taught in Mutex vs semaphore

Priority inversion

H waits on a lock L holds while M keeps L off the CPU. Priority inheritance runs the holder at its highest waiter's priority, bounding H's wait to L's critical section.

Careful: Raising H does nothing; H is blocked.

Taught in Priority inversion

Preventing deadlock

Take locks in one rank order in every task, or give the resource one owner, a gatekeeper task fed by a queue. A timeout turns a freeze into an error you can log; it doesn't prevent one.

Taught in Deadlock

Sizing task stacks

xTaskCreate takes depth in words (4 bytes on Cortex-M). Used = depth − uxTaskGetStackHighWaterMark(); size = used bytes × 1.25 ÷ 4, rounded up. Keep 64 B spare for a task switch.

Taught in Sizing task stacks

Unit 12 Reliability, low power, debugging

Watchdog check-ins

Each task sets its bit once per pass; feed only when every bit is set, then clear them. The timeout must exceed the longest gap between counted feeds, with margin.

Careful: Feeding from a timer interrupt or tick hook every time misses both hung and starving tasks.

Taught in Watchdogs that catch real hangs

Reset cause at boot

Flags stay set until cleared, so an uncleared register piles them up. Leave asserts a note in a .noinit section, trusted only if its marker word is right.

uint32_t cause = RST->CAUSE;   // 1. read first
RST->CAUSE = RST_CAUSE_CLR;    // 2. clear
log_reset_cause(cause);        // 3. keep it

Taught in Reset reasons and asserts

Exception frame

EXC_RETURN bit 2 = 1 means the frame is on PSP (a task); 0 means MSP. PC = 0 with INVSTATE is a null function pointer.

OffsetWord
SP + 0x00 to + 0x0CR0 to R3
SP + 0x10R12
SP + 0x14LR
SP + 0x18PC, the faulting instruction
SP + 0x1CxPSR

Taught in Reading a HardFault

Stop-mode checklist

Unused pins to analog mode. One pull per line. Outputs at the level their pull wants. Peripherals off, dividers switched or made of 1 MΩ. Wake pins stay inputs with the matching pull. Then measure.

Taught in Sleep modes and stray currents

Average current and battery life

Average current is charge per period. Add current × time for every phase, sleep included, then divide by the period. Life = usable fraction × capacity / average current; budget 80 % of a coin cell's rating, and shrink the biggest slice of charge first.

Taught in Battery-life math

The debugging toolbox

Every tool costs time or stops the clock (the probe effect).

ToolCostsUse it for
pin toggle + logic analyzerunder 0.1 µstiming, ISR length
RAM ring-buffer logabout a µsrare events
printf over UART86.8 µs a characterslow code
breakpointhalts the corelogic bugs

Taught in The debugging toolbox