STM32 and the timing budget
Read a timing table, separate the release delay from the execution time, and explain a timing budget, through the reading and the existing, already verified practice set, with the steps and limitations.
Read the Flash and RAM guide before adding a buffer or a task to the firmware
Before you start
Objective: Read a timing table, separate the release delay from the execution time, and explain a timing budget Prerequisite: Can read C/C++ and time units Estimated practice time: 45 minutes. This is a time proposed by the author and has not been measured with real learners.
Comprehension check: Explain one log row with its units, and state that IRQ latency still cannot be measured. Use the results of the existing set to support learning. A successful compile or simulation does not yet confirm the board or real flight.
View the full learning pathway · Review sensors and communication
Choosing an STM32 and reading the firmware structure
STM32 comes in many families, such as F4, F7 and H7. Check the core, clock, FPU, RAM/Flash, timers, DMA, sensor bus, and firmware support according to the actual chip and board model . An FPU helps with supported floating-point work, and DMA helps transfer some types of data, but both still have timing and memory limitations. Start the toolchain from STM32CubeIDE and read the datasheet/reference manual of the chosen model.
A timer is used to set the rhythm and generate signals, while an interrupt lets the system respond to events without polling in a continuous loop. Keep the work in an interrupt handler short, then pass the data on to a suitable task. Using DMA does not by itself make concurrent data access safe. See an example of the roles of the timer, interrupt and DMA in the STM32G0 timer documentation , and re-check the details when using another family.
PX4 divides the sensor, estimator and controller into modules and passes data through uORB, while ArduPilot uses several threads and a scheduler according to the HAL/platform. Moving from Arduino therefore also requires learning task ordering, communication between tasks, and shared resources. Read PX4 architecture v1.16 and ArduPilot threading
Read Flash and RAM before adding firmware work
Objective: Read the sizes from the build separately from memory use at runtime, and make a map that does not add up the same area twice Prerequisite: Can read C/C++, variables, arrays and byte units To begin: Read the guide and do the exercises on a PC or on paper; no board or RTOS is needed yet.

A realistic AI-generated image for an educational context; not a pinout, a chip memory map or a debugger test result
Flash, RAM, stack and heap have different roles
| Term | Basic role | What else to check |
|---|---|---|
| Flash | Stores the program and some data when the power is off | Program area, bootloader and partitions depend on the target; not all of it is always usable |
| RAM | Stores state and data used at runtime | Memory regions and the access restrictions of the chip/SDK |
| Stack | Area for function calls and automatic data | Call depth, local arrays, and the stack of each task and interrupt according to the system |
| Heap | Area that the allocator assigns and returns at runtime | Allocation failure, contiguous block size, and usage over time |
Stack and heap are usually uses of RAM space, not two additional blocks of memory. Do not add RAM + stack + heap capacity as a total capacity. Read the basics of Flash/SRAM from Arduino memory overview and then check the details of the actual target.
Compile figures are not yet the free RAM at runtime
In a typical linker layout, .text relates to code, .data stores static data that has an initial value, and .bss is static data initialised to zero, but the load location and runtime location must be read from the target's linker script/map; for example, .data may have its initial values in Flash and then be copied into RAM at system start. The same data therefore plays a part in both the Flash budget and the RAM budget, and the two budgets should not be merged into a single number.
The names and totals in the size report depend on the format chosen. Read GNU size together with the existing compiler report in this lesson. Do not use the ELF file size on disk in place of the Flash size, or conclude that total RAM minus static RAM equals the real free heap. The reserved stack/system size and the memory regions still matter.
To estimate a buffer from a member count, you must use the real data type and layout. sizeof may include the padding/alignment of a struct, and the pointer size depends on the target. Do not assume that a string always occupies the number of visible characters; allow for a terminator or metadata according to the type used.
Budgeting exercise without double counting
Stated assumptions: RAM available for budgeting is 16 KiB, where 1 KiB = 1,024 bytes, with 4 KiB of static reservation, 3 KiB of total stack and 2 KiB of additional buffers. The three items are separate areas, not already included in one another, and this exercise has no other overhead.
| Item in the exercise | Size |
|---|---|
| Declared capacity | 16,384 bytes |
| static + stack + buffers, kept separate | 9,216 bytes |
| Area not yet allocated in the plan | 7,168 bytes or 7 KiB |
The 7 KiB result is the remainder in the plan under the assumptions not a measured heap or a certified allocation size. If the 2 KiB of buffers are already inside the 4 KiB of static, they must be counted only once: 7 KiB is reserved and 9 KiB remains. In some RTOSes, a task's stack is allocated from the heap, so the overlap must be stated before the figures are added.
Another exercise: There are two free heap blocks, of 4 KiB and 3 KiB, separated by an area still in use. The total free space is 7 KiB, but the largest block is only 4 KiB, so a request for 6 KiB of contiguous space cannot be met, under the assumptions that the allocator needs a single block, that there is no relocation or growth of the area, and that overhead/alignment is not counted. This example illustrates fragmentation; it is not a dump of a real chip.
The diagram shows declared budget categories, not real addresses or a real layout. The size of the RAM bars shows only the proportions in the exercise. Open the full-size memory diagram
Plan the runtime check and begin practising
- Make a copy of the blank memory-planning sheet . Specify the chip/SDK/build/partition, the units and the data source. Mark any value not yet known as unknown.
- Separate the build table, the reserved area and the runtime result. Do the Flash/RAM paper exercise before viewing the answers and scope . The exercise does not add points to the original assessment.
- When a device and a supported SDK are available, plan to record the free heap and the largest free block under the same memory capability and over the checked task period. See Espressif heap information . Do not use the total of all regions in place of the block that the device or DMA can access.
- If you use tasks, check the stack high-water mark with its units according to the port/SDK and the period of operation it covers. The documentation ESP-IDF RAM usage states the value in bytes for the API described. Do not multiply by the word size without checking. A result over the observed period does not yet certify the entire worst case.
- If an allocation fails or abnormal symptoms occur, check the return value, the buffer size and lifetime, double counting and the log before adding memory. Avoid allocations with unpredictable timing in short-period tasks or an ISR, according to the SDK used. Continue to the queue from an ISR to learn about limiting space, and provenance and scope of a log to prepare evidence.
More downloads: Getting-started guide for the memory set · Provenance and assumptions of the memory set · Hash list of the memory files
Budgeting time and checking latency
Hypothetical example: A task intended to run 100 times per second has a period of 10 ms. If reading the sensor takes 2 ms, estimating takes 2 ms, control takes 1 ms and sending the result takes 1 ms, 4 ms remain for other work and margin. This figure is a practice exercise; it is not a benchmark or a rate prescribed for every flight controller.
Measure both the processing time and the age of the data entering the controller. A task may use little CPU but still receive a stale value from a queue. Record the actual period, jitter, missed deadlines, queue backlog, and behaviour when logging or the radio is heavily loaded. If the system is split across several MCUs, the data transmission time, the time synchronisation, and the behaviour when one board resets must also be included in the budget.
STM32 set: practising timing and reading the log
Objective: Build on GPIO/serial on Arduino and ESP32 towards code compiled for an ARM STM32, then read the evidence of which task started late, took a long time, or skipped a period. It suits those who can read C/C++ and timestamps. Start on a PC, without needing a board.
Download the STM32 timing set with code and guide (ZIP) · Reference compile result (JSON) · Answers to the simulated data (JSON) · Timing worksheet (CSV) · File list and SHA-256
Use NUCLEO-F446RE (MB1136) as the reference target for this set; it is not to be generalised to the boards learners have. Built with Arduino CLI 1.5.1, STM32duino 3.0.0 and xPack ARM GCC 14.2.1-1.1; the build passes: program size 18,784/524,288 bytes, static RAM 1,352/131,072 bytes, no warnings found, and re-verified from the ZIP. There is no upload and no LED/serial/timing result from a real board, and PX4/ArduPilot has not been ported to STM32.
The code uses cooperative polling with a period of 10,000 µs (10 ms) from micros() keeping the original phase. When several periods are missed, it performs only the latest period once and counts skipped . It uses only the on-board LED and then writes a CSV row when the buffer has enough space. It does not use a timer ISR/RTOS and does not control motors. The period and the 2,000 µs task budget are a teaching exercise, not a criterion for a flight controller.
Example timeline from synthetic data for teaching; not a measured result from a real board. Open the full-size STM32 timing diagram to see the details enlarged. The realistic image at the top of the lesson is still used to illustrate the concept.
Steps on a PC
- Open the practice set: Extract the ZIP into a new folder and read
README.md,manifest.jsonandcompile-result.json. Keep the folder namestm32_timingand a sketch with the same name. - Check the logic and read the simulated log: Use the Python 3.11+ standard library, run the commands below, and then compare with
synthetic-answers.json. Run the C++ host tests with GNU C++11 if you have a compiler, such as in Ubuntu/WSL. - Compile for the target: In Arduino IDE 2, add the official index/installation method , install STM32 core 3.0.0, choose Nucleo-64 → Nucleo F446RE, generic Serial, USB None, Smallest (-Os) and Newlib Nano, then Verify only, or use the CLI below. No driver or CubeProgrammer installation is needed for the compile step.
- Record and interpret: Fill in the worksheet, separating simulated data from hardware, and check the tool version/options against the receipt. Read
late,work,skippedanddroppedtogether. If you change a task or the period, a new protocol must be collected.
python test_analyze.py
python analyze_timing.py synthetic/normal.csv
python analyze_timing.py synthetic/missed.csv
python analyze_timing.py synthetic/wrap.csv
python analyze_timing.py synthetic/dropped.csv
g++ -std=c++11 -Wall -Wextra -Werror test_timing.cpp -o timing-test
./timing-test
arduino-cli core update-index --additional-urls https://github.com/stm32duino/BoardManagerFiles/raw/main/package_stmicroelectronics_index.json
arduino-cli core install STMicroelectronics:stm32@3.0.0 --additional-urls https://github.com/stm32duino/BoardManagerFiles/raw/main/package_stmicroelectronics_index.json
arduino-cli compile --fqbn STMicroelectronics:stm32:Nucleo_64:pnum=NUCLEO_F446RE --warnings all --clean stm32_timing
In this verification round the SDK was kept only inside the workspace. On Windows, an include path expanded so far that it could not find bits/c++config.h ; a short-named junction to the original official GCC was therefore used, and compiler.path was overridden without modifying the SDK or the system config. If you see the same symptom, use an SDK store with a short path in the project's config. Details are in the README/receipt in the ZIP.
Reading the results and initial cautions
| Value in the CSV | How to read it |
|---|---|
start_us |
Time at which the task check began, as a uint32 in µs |
late_us |
Lateness from the latest period, 0–9,999 µs; a small value may still hide earlier periods that were missed |
work_us |
Time from start, through the scheduler/LED, to the measurement point beforeCSV formatting/serial transmission |
skipped |
Number of old periods not executed this time |
dropped |
Cumulative count of rows that could not be sent since boot; this is not the number of packets lost on the PC |
Simulated example missed.csv: After the task at time 10,000 µs, the next arrival is at 40,100 µs, so two periods, 20,000 and 30,000, are missed, but late from the latest period is only 100 µs. Another row uses work 11,000 µs, exceeding the 2,000 budget, and finishes past the next period. The checker rejects timestamps that go backwards or repeat, a mismatched phase, missing rows that the counters cannot explain, and values with the wrong unit or out of range. Unsigned clock rollover and the edges of the time budget are checked through the host tests.
When dropped increases, the total of skipped/over-budget is only for the rows seen, and there may still be causes in rows that are missing. Formatting/serial work outside work can still delay later tasks. The absence of a reported log drop does not prove that collection began at boot . Split the file after a reset, and do not leave a gap between observed rows of more than 2^31 µs (about 35.8 minutes), so that a wrap can be distinguished from time going backwards; read the details of the limits in the guide.
Real-board step when equipment is available: Check the version/PCB according to ST UM1724 MB1136 and variant STM32duino 3.0.0 before using LD2/PA5 and USART2 PA2/PA3 through the ST-LINK virtual COM according to the default solder bridges. Use only the USB/LED; do not connect an ESC/motor. When ready, upload according to the board manual, open a terminal at 115200 baud, start the capture and then reset to receive the header. Record the log/SHA and the conditions in the worksheet. Change one variable at a time. A blinking LED alone does not certify the timing. ISR/timing measurement on a real board, including DMA/RTOS, remains the next piece of work; the PC-based Timer Interrupt set is in the next topic.
Continue learning and review
Continue with Timer Interrupt and sending the tick · Back to the advanced overview
Practise reading the phase and separating the polling time budget
Objective: Separate late starts, missed periods, over-budget work, and Log rows that could not be sent, and compute the phase and the clock wrap Prerequisite: Can read C/C++, time units, and a five-column CSV Proposed time: 45–60 minutes; not yet measured with real learners. Read the exercises with CSV/JSON; no board or additional installation is needed.
Keep the realistic image and the existing diagram. Use four synthetic CSV cases with 11 original rows in total; the scheduler sequence of seven calls and the numeric edges of the four cases are declared exercises. There are no new analyzer/compile/board run results.
Download the method for practising polling timing, the 8-question timing worksheet, the original data and the declared exercises, the blank row-pair table, the blank scheduler table and the blank report template Do these before reading the answers with reasoning, the row-pair answers and the scheduler answers Check the provenance/SHA-256 from manifest
1. Period, budget and phase · P1–P3
Compute the period from 100 Hz and the budget from the hypothetical example, then fill in all seven row pairs, separating each case before finding differences. Correct the start delta with the late values of both rows to find the scheduled slot delta, then trace the anchor/due of the scheduler over seven calls. Hint: preserve the phase by counting slots, do not set the anchor from now, and a non-due call has no new sample, so leave its result field blank.
2. Separate missed periods from data that could not be sent · P4–P5
Read the missed case where late is only 100 µs but two periods were missed, then separate the count that exceeded the work budget from the count that finished after the next slot. Compare the dropped case where the counter rises by one but skipped in the rows seen is zero. Hint: for the work of a row that is not in the CSV, answer that it is unknown and give the reason; do not invent a value to add in. The dropped total is not packet loss measured on a PC.
3. Clock wrap and threshold edges · P6–P7
Compute the uint32 delta of 4,294,966,000→8,704 µs, then state the half-range limit and any reset before citing the result. Then work through four edge-case examples with work > 2,000 and late + work > 10,000 . Hint: a value equal to the threshold is not strictly greater, and the work budget and finishing after the next slot are separate criteria. The edge examples are numeric exercises, not a board trace.
4. Write a report that states the measurement point · P8
Choose one case and fill in the report template: what is seen → what is not yet known → additional evidence Cite the file, row, pair and unit, and state that the work in the polling set includes the scheduler/LED but is measured before formatting/Serial, so it is not directly compared with the work of the ISR set as a benchmark. The earlier compile result confirms the build target, while the LED/Serial/timing/IRQ on a real board must still be checked separately.
Self-check: This set proposes 2 points per question (1 for the answer + 1 for the reason/unit/boundary), 16 in total. It is for choosing what to review, is separate from the original worksheet, and is not real learner results. This round checked provenance, bytes, numbers and explanations; it did not run the analyzer/host tests or add new compile/upload/firmware/board results. When you can explain it, continue to Timer Interrupt and sending the tick
Choose the next practice set or review
Back to the index of the 10 MCU practice sets to choose a problem according to your goal and the prerequisites you should know, or take the 12-question comprehension assessment to find the topics that should be reviewed.
After checking the answers, record the answers you corrected, the reasons, and what the evidence still does not confirm, then choose the next set that helps answer that question. The worksheet score and the assessment are separate; use them for self-directed selection of review.