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.
Firmware reference
Bit operations, register idioms, timer and serial arithmetic, and the RTOS rules.
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.
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.
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.
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.
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.
Unsigned results wrap mod ; uint8_t 250 + 10 is 4. A signed type's top bit counts negative, so 1111 1111 in an int8_t is −1.
| Type | Range |
|---|---|
uint8_t | 0 to 255 |
int8_t | −128 to 127 |
uint16_t | 0 to 65,535 |
int16_t | −32,768 to 32,767 |
uint32_t | 0 to 4,294,967,295 |
int32_t | −2,147,483,648 to 2,147,483,647 |
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.
RAM use is data + bss in arm-none-eabi-size.
| Declaration | Lives in | Set up by |
|---|---|---|
const global | flash | the programmer |
global or static, nonzero start | RAM, .data | startup copies from flash |
global or static, zero start | RAM, .bss | startup zeroes it |
| plain local | stack | nobody; starts as leftovers |
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.
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 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().
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.
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.
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 if (now && !was) presses++;
was = now; // every pass, after the test Careful: A press shorter than the sample period can be missed.
Take a sample every T from a timer; switch state only when N samples in a row disagree with it. must outlast the bounce (up to 6.2 ms for most switches). Worst delay is bounce + .
Careful: Never time T with a counted loop.
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 */ 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.
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.
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.
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.
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 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.
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.
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.
| Flag | Cleared by | Write |
|---|---|---|
| EXTI->PR bit n | writing 1 | EXTI->PR = 1u << n; |
| TIM3->SR UIF | writing 0 | TIM3->SR = ~TIM_SR_UIF; |
| USART RXNE | reading RDR | b = USART2->RDR; |
Careful: Never |= a write-1-to-clear register; it clears other lines' flags. A flag left set re-enters the ISR forever.
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(); GPIOA->BSRR = 1u << n; // set pin n
GPIOA->BSRR = 1u << (n + 16); // reset pin n Careful: GPIOA->ODR |= bit is a read-modify-write.
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.
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.
Idle high; start bit 0, 8 data bits LSB first, stop bit 1. That is 10 bits per byte.
| Baud | One bit | One byte | Bytes/s, max |
|---|---|---|---|
| 9600 | 104 µs | 1.04 ms | 960 |
| 115200 | 8.68 µs | 86.8 µs | 11,520 |
| 1,000,000 | 1 µs | 10 µs | 100,000 |
Careful: Dividing the baud by 8 forgets the start and stop bits.
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.
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 . Real receivers allow about 3.3–4.4 %; budget under ±2 % per end.
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.
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.
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.
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 Mode = 2 × CPOL + CPHA. A wrong mode shifts every byte by one bit.
| Mode | CPOL, CPHA | SCK idles | Samples on |
|---|---|---|---|
| 0 | 0, 0 | low | rising |
| 1 | 0, 1 | low | falling |
| 2 | 1, 0 | high | falling |
| 3 | 1, 1 | high | rising |
Careful: Slowing SCK doesn't fix a wrong mode.
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.
START, address + write, register, repeated START (no STOP), address + read, data, NACK, STOP. A register write needs one START.
Applies: At most 1000 ns at 100 kHz, 300 ns at 400 kHz. The low end is .
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.
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.
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.
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.
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.
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.
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.
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.
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.
N booleans hold 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.
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.
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.
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.
| State | Meaning |
|---|---|
| Running | has the CPU |
| Ready | could run, waiting for the CPU |
| Blocked | waiting for time or an event; no CPU |
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.
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.
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.
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); 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.
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.
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.
A task notification signals one named task.
| Property | Mutex | Binary semaphore |
|---|---|---|
| Starts | free | empty |
| Owner | the task that took it | none |
| Priority inheritance | always | never |
| From an ISR | not allowed | xSemaphoreGiveFromISR() |
| Use for | guarding a resource | a signal any task may take |
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.
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.
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.
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.
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 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.
| Offset | Word |
|---|---|
| SP + 0x00 to + 0x0C | R0 to R3 |
| SP + 0x10 | R12 |
| SP + 0x14 | LR |
| SP + 0x18 | PC, the faulting instruction |
| SP + 0x1C | xPSR |
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.
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.
Every tool costs time or stops the clock (the probe effect).
| Tool | Costs | Use it for |
|---|---|---|
| pin toggle + logic analyzer | under 0.1 µs | timing, ISR length |
| RAM ring-buffer log | about a µs | rare events |
| printf over UART | 86.8 µs a character | slow code |
| breakpoint | halts the core | logic bugs |
Unfried · getunfried.com/formulas/firmware