A sensor on a wire is only a promise until a driver keeps it. Write one IMU driver three ways and watch the CPU load fall from 11.8% to 3.3% when DMA moves the bytes.
From register map to driver: layers, non-blocking design, event loops and state machines, on an Arm Cortex-M part and a real IMU chip.
Pick a sample rate, then drag the burst size. Watch the same read cost the CPU very different amounts. Then we build, piece by piece, the driver, the layers around it, and the machine that runs it.
You need a little C and the idea that a chip has numbered registers you can read and write. We build the rest from zero.
Built from primary sources, with no course slides: the ST LSM6DSO platform-independent driver, the STM32 HAL SPI header, Valvano’s Embedded Systems: Shape the World (chapter 5, finite state machines) and Elecia White’s Making Embedded Systems. The hero is a model, not a measurement.
A model. The SPI clock is 6.25 MHz (illustrative: 100 MHz bus clock divided by 16). Costs are toy numbers: 1 µs of call overhead for blocking, 1.5 µs per interrupt, 5 µs total for DMA setup and completion. Sample rates are the LSM6DSO’s own 104, 208, 1,667 and 6,667 Hz settings.
Chapter 0
See why one working SPI call on your desk is not yet a driver, and what the other layers promise
You wire an IMU to a Nucleo board. An IMU (inertial measurement unit) is a chip that measures how fast it speeds up and how fast it turns. Your first test is ten lines long. It calls the vendor’s SPI function (SPI is a four-wire serial link between a processor and a chip), waits, and prints six numbers. The numbers change when you tilt the board. It works.
Six weeks later the same ten lines sit inside a robot. A motor loop must run every 1 ms. A radio stack needs the CPU too. The IMU now runs at 6,667 samples a second, about 64 times faster than the 104 in your test. The motor jitters, and the log shows gaps in the IMU samples. Nothing in your ten lines is wrong. They were never a driver.
A driver is the code that owns one device and hides how to talk to it. The rest of the firmware calls imu_read_accel() and gets numbers. It does not know about chip-select pins, byte order or DMA channels. That hiding is a promise, and the promise has four parts.
First, the caller does not wait longer than it agreed to. Second, a failure comes back as an error code, not a hang. Third, the same driver runs on a different chip with a new port file, and runs on your laptop against a fake bus. Fourth, you can say in one table what the driver does in every situation. This lesson builds each part in turn.
Put numbers on the first part. Say your ten lines hold the CPU for 17.64 µs per sample (chapter 3 derives this figure with illustrative clocks). At 104 samples a second that is 0.18% of the CPU, and nobody notices. At 6,667 samples a second it is 11.8%, and one read can delay the 1 ms motor task by up to 17.64 µs every time. The code did not change. The rate did. A promise states the worst case in advance, so the caller can add it to its own budget.
Put a story on the second part. The cable to the IMU works loose for 40 ms. A ten line test returns whatever bytes it holds, and the robot trusts them. A driver returns a code such as “bus error” and lets the caller choose: skip this sample, stop the motors, or raise an alarm. The driver does not decide policy. It makes sure the caller learns the truth.
Look at what one call really does. The device below follows one call down through four layers. Each layer turns a request into something more concrete. At the bottom there are only bits on two wires.
Pick a call. A dot falls through the application, the driver, the port and the bus. Each box shows what that layer turns the request into.
Register addresses and values are from ST’s LSM6DSO driver header (WHO_AM_I 0x0F, CTRL1_XL 0x10, OUTX_L_A 0x28, ID 0x6C). The 0x80 read flag is the usual SPI convention for this family. The clock count assumes 8 clocks per byte and one address byte.
Notice the width of the promise. The caller said four words. The wires carried a handful of bytes. Every layer between them is a place where something can be slow, wrong or blocked.
The rest of the lesson follows that fall. Chapter 1 reads the chip’s register map (the numbered list of settings and results inside the chip) and writes the thinnest possible driver. Chapter 2 splits the driver from the board. Chapters 3 to 5 make the read cost less CPU time. Chapters 6 and 7 give the driver a place to run and a machine to track its work. Chapter 8 handles failure and tests all of it without a board.
This lesson builds on buses on the wire for SPI itself and on timers and sampling for why sample times matter. If you want the vocabulary of a microcontroller first, start with the embedded systems introduction.
Chapter 1
Read one ID byte and six data bytes from a real IMU, and turn raw counts into milli-g
Open the datasheet of any sensor and you find a table with two columns: an address and a name. That table is the register map. A register is one byte inside the chip with a number. Some registers hold settings you write. Some hold results you read. The chip does nothing until you write the right bytes to the right addresses.
We use the ST LSM6DSO, a 6-axis IMU, because ST publishes its driver as open source. Three addresses carry the story. WHO_AM_I is at 0x0F and always reads 0x6C, so it proves the wiring works. CTRL1_XL is at 0x10 and sets the accelerometer rate and range. The six result bytes start at OUTX_L_A, address 0x28.
The chip also has a STATUS_REG at 0x1E. Its bit 0, XLDA, is 1 when a new accelerometer sample waits for you. Bit 1, GDA, says the same for the gyroscope. Keep these in mind: chapter 5 uses them.
On SPI (serial peripheral interface), the controller pulls a chip-select line low, then clocks bytes out on one wire while bytes come back on another. The first byte is always an address. For a read, you set its top bit: address 0x28 becomes 0xA8. The chip then sends the register’s value while you clock out dummy zeros. If you forget the top bit, the chip hears a write.
The result registers sit in a row: X low, X high, Y low, Y high, Z low, Z high. The chip moves its internal address up by one after each byte when the IF_INC bit in CTRL3_C (0x12) is on. So one frame of 1 address byte plus 6 data bytes reads all three axes. That is a burst read.
Build the frame yourself. The device below is a model of the chip. It shows the four SPI wires for the frame you choose.
Choose a register. The traces show what the controller sends and what the chip answers. Then clear the read flag and see what the chip hears.
A model of the bus, not a capture. IDs, addresses and the 0.061 mg per count scale are from ST’s LSM6DSO driver. The sample bytes are illustrative: a board tilted a little, X = +120 mg, Y = −50 mg, Z = +990 mg.
Now the worked example. The bytes after the address are AF 07 CC FC 66 3F. The low byte comes first on this chip, so X is 0x07AF, which is 7 × 256 + 175 = 1,967 counts. At the ±2 g range, ST’s driver multiplies each count by 0.061 to get milli-g: 1,967 × 0.061 = 120.0 mg. Y is 0xFCCC. That is 64,716 as an unsigned number, so as a signed 16-bit number it is 64,716 − 65,536 = −820 counts, or −50.0 mg. Z is 0x3F66 = 16,230 counts = 990.0 mg, almost exactly 1 g, the pull of gravity.
The signed step is the part beginners miss. A two’s complement number uses the top bit as a negative weight. If you cast to uint16_t, the Y axis reads +64,716 and your robot thinks it is falling upward.
This is the driver in its thinnest form. Here is the C, close to what ST’s own code does:
c#define LSM6DSO_WHO_AM_I 0x0F #define LSM6DSO_CTRL1_XL 0x10 #define LSM6DSO_OUTX_L_A 0x28 #define LSM6DSO_ID 0x6C static int read_reg(uint8_t reg, uint8_t *buf, uint16_t len) { uint8_t tx[7] = { reg | 0x80 }, rx[7]; /* read flag */ cs_low(); int rc = HAL_SPI_TransmitReceive(&hspi1, tx, rx, len + 1, 5); cs_high(); for (uint16_t i = 0; i < len; i++) buf[i] = rx[i + 1]; return rc; } int imu_read_accel_mg(float mg[3]) { uint8_t b[6]; if (read_reg(LSM6DSO_OUTX_L_A, b, 6)) return -1; for (int i = 0; i < 3; i++) { int16_t raw = (int16_t)(b[2*i] | (b[2*i + 1] << 8)); mg[i] = raw * 0.061f; /* +-2 g range */ } return 0; }
The data flow is plain: a register address goes in, a byte array comes out, and a scale factor makes it a physical unit. The scale factor depends on the range setting in FS_XL (bits 3:2 of CTRL1_XL). ST’s driver ships separate converters for each range, with 0.061 for ±2 g, 0.122 for ±4 g and 0.244 for ±8 g. If you change the range and forget the scale, every number is wrong by a clean factor of two or four.
Here is a trap that costs an afternoon. You wire the chip, read WHO_AM_I and get 0x6C. You read the six data registers and get zeros. The wiring is fine. The sensor is simply off. In ST’s driver the rate code 0 is LSM6DSO_XL_ODR_OFF, and a chip with its rate set to off does not measure.
The symptom is steady zeros. The measurement is STATUS_REG: the XLDA bit never becomes 1, because no sample is ever made. The fix is one write. Put a rate code in the top nibble of CTRL1_XL. The rate codes in the driver header are 4 for 104 Hz, 5 for 208 Hz, 8 for 1,667 Hz and 10 for 6,667 Hz. So 104 Hz is the byte 0x40, and 6,667 Hz is 0xA0.
The byte CTRL1_XL holds three settings at once. Bit 1 is lpf2_xl_en. Bits 3 and 2 are fs_xl, the range. Bits 7 to 4 are odr_xl, the rate. If you write 0x40 to change the rate, you also write zero into the range field and the filter bit. You may have set a different range a moment ago, and this write silently undoes it.
The safe pattern is read, modify, write. Read the byte. Clear only the bits you own with a mask. Set your new bits. Write the byte back. To change only the rate, the mask is 0xF0. To change only the range, the mask is 0x0C. In C the middle step is v = (v & ~0xF0) | (code << 4). One extra SPI read is a small price for a setting that never clobbers its neighbour.
Worked example. The byte reads 0x04, which means some range code and rate off. You want 104 Hz, which is code 4. Mask: 0x04 & ~0xF0 = 0x04. Shift the code: 4 << 4 = 0x40. Combine: 0x04 | 0x40 = 0x44. Write 0x44. The range bits stayed as they were, and only the rate changed.
One more habit makes drivers easy to debug: after you write a setting, read it back and compare. If the chip still shows the old value, the write never arrived, and you know the problem is the bus, not your logic. Chapter 8 turns this check into a rule.
uint16_t. The board lies still, tilted a little, but Y reads +64,716 counts. What went wrong?Chapter 2
Split the driver from the board with one small struct of function pointers, then sort real lines of code into their layers
Your IMU driver works on the Nucleo. Next month the team moves to a board with a Nordic nRF52840. The SPI calls differ. The chip-select pin differs. You open the driver and find HAL_GPIO_WritePin on line 40, in the middle of the code that scales milli-g. You now have to edit code that has nothing to do with the new board. Each edit can break something that worked.
The fix is a rule: each file knows about one kind of thing. The chip file knows the chip. The board file knows the board. The application knows what it wants to do. Three kinds of knowledge give three layers.
A HAL (hardware abstraction layer) is the layer that hides one microcontroller’s peripherals behind a common set of calls. ST ships one for STM32, and Nordic ships a different one for nRF52. A port is the thin file you write that connects your driver to whichever HAL the board uses. In older code you may see the same idea called a board support package, or BSP.
ST’s open-source LSM6DSO driver shows the pattern clearly. The driver never calls SPI. It calls two function pointers that you hand it. The struct is named stmdev_ctx_t. It holds write_reg, read_reg, an optional mdelay, and a void *handle that the port can use for anything, such as a pointer to the SPI handle. Both register functions take the handle, a register address, a buffer and a length, and return an int32_t status.
c/* the driver's whole view of the board (from ST's lsm6dso_reg.h) */ typedef int32_t (*stmdev_write_ptr)(void *handle, uint8_t reg, const uint8_t *buf, uint16_t len); typedef int32_t (*stmdev_read_ptr) (void *handle, uint8_t reg, uint8_t *buf, uint16_t len); typedef struct { stmdev_write_ptr write_reg; stmdev_read_ptr read_reg; /* ... */ void *handle; } stmdev_ctx_t; /* port file for an STM32: the only place that knows HAL_SPI and the CS pin */ static int32_t port_read(void *h, uint8_t reg, uint8_t *buf, uint16_t len) { uint8_t r = reg | 0x80; /* read flag: this port's choice */ cs_low(); HAL_SPI_Transmit((SPI_HandleTypeDef *)h, &r, 1, 5); HAL_SPI_Receive ((SPI_HandleTypeDef *)h, buf, len, 5); cs_high(); return 0; } stmdev_ctx_t imu = { .write_reg = port_write, .read_reg = port_read, .handle = &hspi1 };
The driver’s body is then plain C. lsm6dso_device_id_get(&imu, &id) reads one byte from 0x0F by calling imu.read_reg(imu.handle, 0x0F, &id, 1). In ST’s repository the header includes only stdint.h, stddef.h, math.h and string.h, and the 11,936 line source file contains no HAL call. The same files run on any chip.
Which way do the arrows point? The application calls the driver. The driver calls the port through the struct. The port calls the HAL. Nothing points up. The driver never calls the application, and it never includes a vendor header. That one-way rule is what lets you swap the board.
There is a cost. A call through a function pointer is one extra jump. On a Cortex-M that is a few cycles, much less than the SPI byte it carries. The real cost is that you must decide where each piece of knowledge lives. Try it.
Each line of code belongs in one layer. Pick a layer for every line, then press Check. Wrong lines turn red and say why.
The lines are illustrative C for an LSM6DSO on an STM32. Where the 0x80 read flag lives (driver or port) is a design choice, so no line above tests it. Pick one place and write it in the port’s header comment.
Count what the port bought you. To move from the Nucleo to the nRF52840 you rewrite one small file: the SPI transfer, the chip-select pin and the delay. The register scaling, the ID check and the rate table stay as they are. You also get a second gift. In a unit test on your laptop, you hand the driver a fake port that pretends to be the chip. Chapter 8 does exactly that.
A good port stays small. It has no loops that decide anything and no knowledge of what the bytes mean. If you find an if about a register value in the port, move it up into the driver.
The test for a layer. Ask: what changes if I swap this part? Swap the board, and only the port changes. Swap the chip, and only the driver changes. Swap the product, and only the application changes.
Picture the team that did not draw the line. The driver file includes the vendor header and calls HAL_SPI_Transmit in six places. A teammate wants to unit-test the scaling code on a laptop. The file will not compile there, because the laptop has no stm32f4xx_hal.h. The teammate copies the scaling function into a test file. Now two copies exist. A month later someone fixes a rounding bug in one and not the other. The test passes while the firmware is wrong.
The symptom is a green test and a wrong number on the device. The measurement is a plain search: grep the driver directory for the letters HAL_, and every hit is a leak. The fix is to move each hit into the port, and to leave a function-pointer call in its place.
ST’s struct has five fields, and each one is a small contract. read_reg and write_reg move bytes and return zero on success. mdelay waits a number of milliseconds, for the steps where a chip needs time to settle, such as after a reset. handle is an opaque pointer that the driver passes back untouched, so the port can find its SPI instance without a global. priv_data is spare room for the port. The driver never looks inside either pointer.
You can tighten the contract for your own driver. Add start_dma for chapter 4 and now_us for the timeouts of chapter 8. Document what each function may do. For example: “read_reg blocks for at most 2 ms and returns a non-zero code on any failure.” That sentence is the port’s half of the promise from chapter 0.
Count the cost in plain numbers. The indirect call adds a load and a jump, a few cycles. One SPI byte at 6.25 MHz takes 128 cycles of a 100 MHz core. The call is under a tenth of one byte. The abstraction is cheap, and it buys a driver that builds on any machine.
You can also choose the layer boundary at link time instead of through a struct. Define the port functions with fixed names and compile only one port file into each build. That removes the pointer call and costs you the ability to run two ports in one program, which a test needs. Pick the struct when you plan to test on a laptop.
stm32f4xx_hal.h, a board call leaked into the driver. Fix that before it spreads.#include "stm32f4xx_hal.h". What is the real cost?Chapter 3
Write the simplest read, count its cost in microseconds and cycles, and see which other task it makes late
A robot arm runs a control task every 250 µs. It reads a joint angle, does a little maths and sets a motor current. On the same Cortex-M, your IMU driver reads a sample 6,667 times a second. Both tasks are correct alone. Together, the control task sometimes starts late, and the arm shakes.
The cause is the first driver style. A blocking call does not return until its work is finished. The vendor HAL names it plainly: HAL_SPI_TransmitReceive(hspi, pTxData, pRxData, Size, Timeout). The CPU sits inside that call, in a loop, watching a status flag. It cannot do anything else.
That loop is called polling: asking again and again, “is it done yet?” Polling is easy to write and easy to debug. You can step through it with a debugger. Many drivers should start here.
The bus decides how long the call lasts. An SPI byte takes 8 clocks. A read of 12 data bytes sends 1 address byte too, so it moves 13 bytes, which is 104 clocks. At a 6.25 MHz SPI clock one clock takes 0.16 µs, so the frame takes 104 × 0.16 = 16.64 µs. On a 100 MHz core, 16.64 µs is 1,664 CPU cycles spent waiting for wires. (Both clock speeds are illustrative; yours will differ.)
Add 1 µs of call overhead and the CPU is busy for 17.64 µs per sample. At 6,667 samples a second the sample period is 150 µs. The CPU load is 17.64 / 150 = 11.8%. At 104 Hz the period is 9,615 µs and the load is 0.18%. The same code is harmless at one rate and heavy at another.
Load is not the whole story. What hurts the control task is that a simple main loop cannot pause the read halfway to run it. If the IMU read starts at t = 0 and the control task is due at t = 5 µs, it waits 12.6 µs. Try it. The device runs both tasks on one CPU, one after the other, and measures how late the control task starts.
Orange blocks are CPU time. The top lane is the IMU read, the bottom lane is the control task. A red gap is time the control task waited after it was due.
A model. The control task is due every 250 µs and needs 40 µs (illustrative). Both tasks run one after the other on one CPU with no preemption. The blocking call costs the bus time plus 1 µs. Rates are the LSM6DSO’s 104, 208, 1,667 and 6,667 Hz codes.
Set the burst to 120 bytes and the rate to 6,667 Hz. A 121 byte frame takes 154.9 µs at 6.25 MHz. That is longer than the 150 µs sample period. The driver can never catch up, and the chip overwrites samples. In this model a blocking driver breaks in two ways: it delays other work, and it can fall behind the sensor.
The last HAL argument, Timeout, is in milliseconds. It says how long the call may spin before it gives up. If you pass HAL_MAX_DELAY, it waits forever, and a loose wire hangs your whole firmware. A 5 ms timeout on a 150 µs sample period means one stuck bus costs 33 samples of silence. Chapter 8 returns to timeouts. For now, never write an infinite wait.
c/* style 1: blocking. Simple, steppable in a debugger, costs the CPU the whole bus time. */ int imu_read_blocking(int16_t raw[6]) { uint8_t tx[13] = { 0x22 | 0x80 }, rx[13]; /* OUTX_L_G, then 12 bytes */ cs_low(); HAL_StatusTypeDef rc = HAL_SPI_TransmitReceive(&hspi1, tx, rx, 13, 2); cs_high(); if (rc != HAL_OK) return -1; for (int i = 0; i < 6; i++) raw[i] = (int16_t)(rx[1 + 2*i] | (rx[2 + 2*i] << 8)); return 0; }
Notice what blocking gets right. There is no shared state. The buffer lives on the stack. There is no moment when the driver is half done, so there is no bug that appears only when two things overlap. When the load is low, say below a few percent, blocking is a fine answer. Many production drivers for slow sensors never leave this style.
Blocking is not a beginner’s mistake. Use it when the call is rare or the CPU has nothing better to do. The chip configuration at boot is the clearest case: you write five registers once, nothing else is running yet, and the code reads like a recipe. A sensor sampled at 10 Hz, such as a temperature chip, costs a tiny fraction of one percent. A debugger can step straight through the call.
Use the numbers to decide. Write down three figures: the longest block in microseconds, the shortest deadline of any other task, and the sample rate. If the longest block is much shorter than the shortest deadline, and the load is a few percent, stay with blocking. In our example the longest block is 17.64 µs and the control deadline is 250 µs, so a single read fits. The trouble starts when the burst grows to 120 bytes, which blocks for 154.9 µs, or when the clock drops to 3.1 MHz and the same 13 byte frame takes 33.3 µs.
Two details hide inside the blocking call. First, chip select. The driver pulls the line low, calls the HAL, and raises it again. The chip needs a short setup time between chip select and the first clock, and a hold time at the end. A fast core can violate both unless the port adds a few NOP instructions or a short delay. The symptom is a first byte that is occasionally wrong. You find it by capturing CS and SCK on a logic analyzer and measuring the gap in nanoseconds against the datasheet.
Second, an interrupt that fires during a blocking read lengthens it. If a 10 µs interrupt arrives in the middle of your 17.64 µs read, the read finishes at about 27.6 µs. The timeout you set for the HAL call must include the worst interrupt load, not just the bus time. A 2 ms timeout on a 17 µs transfer is generous. A 20 µs timeout would fire by accident.
There is also the polling form of data-ready. A blocking driver may read STATUS_REG in a loop until XLDA is 1. Every poll is a full 2 byte SPI frame, 16 clocks, 2.56 µs at 6.25 MHz. Polling at the full speed of the bus can keep the CPU 100% busy to catch a sample that arrives once every 600 µs. Give the loop a bound, and give it a pause between checks.
Chapter 4
Start the transfer, return at once, and find out when an interrupt per byte helps and when DMA wins
Blocking makes the CPU watch the wires. The obvious fix is to let the CPU leave and come back when the wires finish. The chip has two ways to call it back, and they cost very different amounts.
The first is an interrupt: a signal that makes the CPU stop what it is doing, run a short function called the interrupt service routine (ISR), and then go back. In the vendor HAL the call is HAL_SPI_TransmitReceive_IT(hspi, pTxData, pRxData, Size). It starts the transfer and returns at once. Then the SPI peripheral raises an interrupt for each byte, and the HAL’s handler moves that one byte. When the last byte lands, the HAL calls your function HAL_SPI_TxRxCpltCallback(hspi).
The second is DMA (direct memory access): a small engine on the chip that copies bytes between memory and a peripheral with no CPU involved. HAL_SPI_TransmitReceive_DMA takes the same arguments. The CPU sets up the buffer and the length, goes away, and gets exactly one interrupt at the end, the same TxRxCpltCallback.
Both calls return immediately. While a transfer runs, HAL_SPI_GetState reports HAL_SPI_STATE_BUSY_TX_RX (value 5), and a second start request will not be accepted until the state is back to READY (value 1).
An interrupt is not free. The CPU must save its registers, jump to the handler, run it and restore everything. Say that costs 1.5 µs per interrupt (an illustrative figure for a HAL handler on a 100 MHz core; measure yours). With one interrupt per byte, a frame of 13 bytes costs 13 × 1.5 + 2 setup = 21.5 µs of CPU time.
Compare that with blocking, which took 17.64 µs for the same frame. The interrupt version is worse. The reason is simple. At a 6.25 MHz clock one byte takes 8 / 6.25 = 1.28 µs to cross the wire. The interrupt costs 1.5 µs. The CPU spends more time entering the handler than the byte spends travelling. Waiting would have been cheaper.
The rule has a crossover. Interrupt per byte beats blocking only when the cost of one interrupt is smaller than the time of one byte. Slow clocks make bytes long, so interrupts win. Fast clocks make bytes short, so interrupts lose. At 6.25 MHz with 1.5 µs, they lose. The same ISR would win at 1 MHz, where a byte takes 8 µs.
If the ISR is slower than a byte, there is also a hard failure. The next byte arrives before the handler has read the last one, and the SPI peripheral sets an overrun error. Bytes are lost. In this model the hero flags that case.
DMA changes the arithmetic. Its CPU cost does not depend on the length. You pay setup (3 µs here) and one completion interrupt (2 µs), 5 µs in total, for 2 bytes or for 120. Explore the curves.
Each line is the CPU time one burst costs. Lower is better. Drag the burst marker, the SPI clock or the interrupt cost, and watch the lines cross.
A model with toy costs: blocking = bus time + 1 µs, interrupt = (bytes + 1) × the interrupt cost + 2 µs, DMA = 3 µs setup + 2 µs completion. Measure your own part before you trust any of them.
c/* style 3: DMA. The buffers must outlive this function: DMA writes into them later. */ static uint8_t g_tx[13] = { 0x22 | 0x80 }; static uint8_t g_rx[13]; int imu_start_read_dma(void) { if (HAL_SPI_GetState(&hspi1) != HAL_SPI_STATE_READY) return -1; /* one at a time */ cs_low(); return HAL_SPI_TransmitReceive_DMA(&hspi1, g_tx, g_rx, 13) == HAL_OK ? 0 : -1; } void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *h) { /* runs in interrupt context */ cs_high(); g_sample_ready = 1; /* do not parse here: set a flag */ }
Two traps wait in that code. First, the buffers are static. If you declared rx as a local variable, the function would return, the stack space would be reused, and DMA would later write six bytes of IMU data into whatever lives there now. The symptom is random corruption in unrelated variables. You find it by checking that the address DMA writes to is not on the stack. You fix it by giving the buffer a longer life.
Second, the callback runs in interrupt context, so it does as little as possible. It raises chip select and sets a flag. The main loop does the parsing. Chapter 5 turns that flag into a proper handshake. On parts with a data cache, such as a Cortex-M7, you must also invalidate the cache over g_rx before you read it, because DMA writes to memory behind the cache’s back.
You now have three tools, so here is a rule of thumb that you can check against your own measurements. Take the time of one byte on the wire, 8 divided by the clock in MHz. Call it b. Take the cost of one interrupt in your system and call it i.
If the whole transfer is shorter than the setup and completion cost of DMA, which is 5 µs here, use blocking. If i is clearly smaller than b, as on a slow bus, an interrupt per byte is a reasonable middle choice because it needs no DMA configuration. If the burst is longer than a few bytes and the clock is fast, use DMA. At 6.25 MHz, DMA overtakes blocking at 3 data bytes in this model, because 5 µs is smaller than the 8 × 4 / 6.25 + 1 = 6.1 µs that blocking costs for 3 data bytes (and 4.8 µs for 2).
In cycles, on the 100 MHz core, the 13 byte frame costs 1,764 cycles blocking, 2,150 with an interrupt per byte, and 500 with DMA. Those figures come from the toy costs and will move on your part. What stays true is the shape: two lines that rise with the burst and one flat line.
The vendor call hides a few settings, but you should know they exist. A DMA transfer needs a source, a destination and a count. For SPI the engine also needs two channels, one that feeds the transmit register and one that drains the receive register. In normal mode it stops after the count. In circular mode it restarts by itself, which suits an ADC and not a register read that needs a fresh chip-select each time. Normal mode fits our IMU burst.
Alignment matters too. The buffer should be aligned to the width of the transfer. A byte buffer is always fine. A 32-bit buffer that starts at an odd address can fault. A symptom is a bus fault the first time the second sample is read, and the measurement is the faulting address in the fault status registers. The fix is to align the array.
Last, the stack trap deserves its worked example. The function declares uint8_t rx[13] as a local, starts DMA and returns. The stack pointer moves up. Two microseconds later the caller calls another function, which places its own locals over the same bytes. When the DMA finishes, it writes 13 bytes of IMU data over that function’s variables. The symptom is a counter that jumps for no reason. The cure is the one in the code above: static buffers with a clear owner.
TxRxCpltCallback. Drive a second pin high on ISR entry and low on exit. A logic analyzer shows the three styles side by side: the ISR pin in the interrupt style pulses 13 times, in the DMA style it pulses once.Chapter 5
Let the chip tell you when a sample waits, hand it from interrupt to main loop, and size the queue so nothing is lost
Your DMA driver starts a read and returns. Two questions now matter. When should it start the next read? And when the read ends, who may touch the bytes? A good answer to both is a handshake: a short, agreed exchange between two parties so that neither one steps on the other.
You can start reads on a timer. That wastes reads when no new sample exists, and it misses samples when your timer drifts. The IMU offers a better signal. It has a data-ready output on its INT1 pin. You turn it on by setting bit 0 of INT1_CTRL (address 0x0D), the bit ST’s header calls int1_drdy_xl. Every time the chip finishes a new accelerometer sample, the pin signals it.
Connect INT1 to a GPIO that raises an interrupt. The chain is then: the chip finishes a sample, INT1 fires, a tiny ISR starts the DMA read, the DMA completes, the callback marks the data ready for the main loop. Nothing waits, and nothing polls. The sample rate is set by the chip’s own clock, not by your timer.
If you cannot wire the pin, the same fact lives in a register. STATUS_REG (0x1E) has the XLDA bit. Polling it costs one extra SPI frame of 2 bytes per check, so it is a fallback, not a first choice.
The buffer g_rx has a clear life. While the DMA runs, the DMA engine owns it: nobody else may read it, because it holds half-written bytes. When the completion callback runs, ownership returns to the CPU. The driver must copy the sample out (or swap to another buffer) before it starts the next read, or the next DMA overwrites the data the application is still using.
The usual tool is a ring buffer, a fixed array used in a circle with a write index and a read index. The interrupt side writes at the head, the main loop reads at the tail, and each side changes only its own index. With one writer per index, no lock is needed. A queue of depth D holds up to D samples.
How big must D be? Think of the main loop as a person who sometimes leaves the room. The chip delivers one sample every period. If the loop is away for S, then S divided by the period samples pile up, and the queue must hold that many. At 1,667 Hz the period is 600 µs. A 5 ms stall (a flash write, say) lets 8.3 samples arrive, so D must be at least 9. Test your own numbers.
The IMU delivers a sample every 600 µs. The main loop normally drains the queue each millisecond, then stalls every 50 ms. Red crosses are samples lost because the queue was full.
A model. Samples arrive at 1,667 Hz, one every 599.9 µs (the LSM6DSO rate code for 1,667 Hz). The main loop drains the whole queue every 1 ms, except during a stall that starts at 10 ms and repeats every 50 ms. The stall length is illustrative.
Now the code for the handoff. The ISR side and the main side share one array and two indices. Each index has one writer.
c/* single producer (DMA callback), single consumer (main loop): no lock needed */ #define QN 16 static volatile uint16_t q_head, q_tail; /* head: ISR writes; tail: main writes */ static imu_sample_t q[QN]; static volatile uint32_t q_dropped; void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *h) { cs_high(); uint16_t next = (q_head + 1) % QN; if (next == q_tail) { q_dropped++; } /* full: count it, never block */ else { unpack(g_rx, &q[q_head]); q_head = next; } } bool imu_pop(imu_sample_t *out) { /* called from main loop */ if (q_tail == q_head) return false; *out = q[q_tail]; q_tail = (q_tail + 1) % QN; return true; }
Look at q_dropped. A driver that loses data silently is a trap. A driver that counts it gives you a number to watch. In production firmware, this counter belongs in the telemetry. Chapter 8 returns to it.
The data-ready line also removes a classic race. If you start the next read from a timer, the timer may fire while the previous DMA still runs. The HAL then refuses the call, since the SPI state is not READY, and you silently skip a sample. Start from the chip’s own signal, and check the state anyway.
Take a queue with QN = 4. The code keeps one slot empty so that “full” and “empty” look different: empty means head equals tail, and full means head + 1 equals tail. So this ring holds at most 3 samples, and QN = 16 in the code above holds 15. When you size by the rule of chapter 5, add that spare slot.
Start with head = 0 and tail = 0. Sample A arrives. The callback writes slot 0 and sets head = 1. Sample B arrives: slot 1, head = 2. The main loop wakes, pops slot 0 (A), and sets tail = 1. Sample C: slot 2, head = 3. Sample D: next would be (3 + 1) % 4 = 0, which is not equal to tail (1), so slot 3 is written and head = 0. Sample E: next would be 1, which equals tail, so E is dropped and q_dropped becomes 1. Every step changed exactly one index from exactly one side.
The data-ready line reaches the CPU as an external interrupt on a GPIO. On an STM32 the EXTI block detects a rising or falling edge. An edge is a moment, not a level. If a second sample arrives while you are still handling the first, the line may rise again before the first request is cleared, and one edge is lost. If the chip offers a sample counter or timestamp, you read it and compare, so a lost edge is seen. If it does not, count the edges you handle against the samples you expect from the rate.
The ISR for the pin should do two things: clear the pending bit and push E_DRDY into the event queue. It does not start SPI itself unless it is very short. Starting the DMA from the ISR is allowed, since the call only sets registers, and many drivers do it to save a loop pass. The rule is that nothing in the ISR waits.
A last number to keep in mind: the whole chain, from INT1 rising to the sample sitting in the ring, takes the ISR time, the DMA time and the callback time. In the model that is about 1.5 + 3 + 16.6 + 2 = 23 µs. At 1,667 Hz you have 600 µs per sample, so the chain uses under 4%. At 6,667 Hz you have 150 µs and it uses 15%. If the chain were longer than the period, the driver could never keep up, and no queue could save it.
q_dropped for your queue depth.Chapter 6
Run the driver, a control task and a logger in one loop, and learn why one slow step makes everything late
The queue from chapter 5 needs someone to empty it. That someone is the main loop. A small product has a handful of jobs: drain IMU samples, run a control step every millisecond, send a log line every 50 ms, check a button. You could give each job its own thread under an RTOS. Many products do not. They use one loop.
This shape is called a super loop or event loop: while (1) around a list of checks. Each check asks, “does my job have something to do?” If yes, it does a small piece of work and returns. Elecia White’s Making Embedded Systems covers this under managing the flow of activity: the main loop, where to use interrupts, and how to build a state machine. Valvano’s chapter 5 teaches the state machines that such loops run.
The interrupt side stays tiny. The SysTick timer sets a flag every millisecond. The SPI callback sets a flag or pushes into the queue. Interrupts only record that something happened. The loop does the work. This split keeps interrupts short, which keeps every other interrupt responsive.
cvolatile uint8_t tick_1ms; /* SysTick ISR: tick_1ms = 1; */ int main(void) { board_init(); imu_init(); logger_init(); for (;;) { imu_sample_t s; while (imu_pop(&s)) filter_update(&s); /* job 1: drain the queue */ if (tick_1ms) { tick_1ms = 0; control_step(); } /* job 2: every 1 ms */ logger_step(); /* job 3: small steps only */ __WFI(); /* sleep until the next interrupt */ } }
The loop obeys one law, run to completion: each job finishes its piece before the next job starts, and nothing interrupts a job except an ISR. This makes shared data easy. Two jobs never touch the same variable at the same time, so you rarely need a lock. The price is a promise: no job may run long.
Break the promise and see. The logger formats a line and sends it over a slow UART. If it waits for the UART to finish, it holds the loop for milliseconds. In that time the 1 ms control tick is missed and the IMU queue fills. Use the device to cause the problem, then fix it by cutting the logger into small steps.
Three lanes over 40 ms. The logger job comes due at 10 ms. Stretch it, then turn on small steps and watch the control task recover.
A model with toy numbers. IMU samples arrive every 600 µs and each takes 20 µs to filter. The control step is due every 1 ms and takes 100 µs. The logger is due at 10 ms and again at 60 ms. The loop is cooperative: no job is stopped once it starts.
The fix is a change in how you write the job, not in the loop. The logger no longer says, “send this whole line, then return.” It says, “send the next 16 bytes, remember where I stopped, then return.” The memory of where it stopped is a state. That is the bridge to the next chapter: a job that does a little and returns needs a variable that tells it what to do next.
Run the arithmetic for the failure. With an 8 ms logger that starts at 10 ms, the control step due at 11 ms cannot start until about 18 ms, so it is about 7 ms late. The steps due at 12 to 17 ms also wait, then run in a burst when the logger ends. The motor sees no update for 8 ms, then several at once. Measured with a GPIO toggle per job, the symptom shows up as a gap in the control lane. That measurement is the first thing to take on real hardware.
In a super loop, a deadline is met when the longest single pass is short enough. Write the worst case of each step in microseconds. In our example the IMU drain takes 20 µs per sample, and up to eight samples can wait, so 160 µs. The control step takes 100 µs. The logger takes up to 400 µs per step when it is split. One bad pass has all three: 160 + 100 + 400 = 660 µs. The shortest deadline is the 1 ms control tick, so the loop fits with 340 µs to spare.
The same sum with the unsplit 8 ms logger gives 160 + 100 + 8,000 = 8,260 µs, over eight ticks. The sum predicts the failure before you run anything. Do this sum for every new job you add to the loop. It takes a minute.
The code above uses a flag, tick_1ms. A flag has a flaw: if two ticks arrive before the loop looks, the flag is still 1, and one tick is lost without a trace. A counter fixes this. The SysTick ISR does ticks++. The loop remembers handled. It runs control_step while handled != ticks and increments handled each time. If the gap between the two is ever bigger than 1, the loop is late, and you can record how late. That one number tells you if your sum was right.
Sleep is the other detail. The line __WFI() halts the core until the next interrupt arrives. The core draws far less current while it waits. Because every event source is an interrupt, the loop wakes exactly when there is work.
There is one race to avoid. Suppose the loop checks its flags and finds none. Then an interrupt fires and sets a flag. Then the loop reaches __WFI() and sleeps, with work waiting. The usual fix is to disable interrupts with PRIMASK, check the flags again, call __WFI(), and enable interrupts. A Cortex-M core still wakes on an interrupt that is pending while PRIMASK masks it, so the pattern does not lose the wake-up. Confirm this in your core’s reference manual.
The event loop works while jobs are short, few and equally important. It struggles when a job must wait for something long, such as a flash erase that takes tens of milliseconds, or when two jobs have very different deadlines and the slow one cannot be split. Then you move that job to a thread under an RTOS, which can preempt it. The survey lesson on RTOSes shows how. Most sensor nodes never need that step, and a well-split loop is easier to reason about.
Chapter 7
Replace a pile of flags with five named states and one table, then fire events and watch the machine decide
Your non-blocking driver has grown flags. is_reading is true while a DMA runs. has_error is set when it fails. retrying is set while the SPI is reset. A new teammate adds initialised. Three weeks later a field unit reports that it never reads again after one cable glitch. The cause: is_reading stayed true after the error, so the driver thinks a read is still running and never starts another.
Four flags can be in 16 combinations. Only a handful are legal. Nothing in the code says which. Each new if guesses at the rest.
A finite state machine (FSM) replaces the flags with one variable: the state, a name for “what the driver is waiting for right now.” It has a fixed list of states. It reacts to events, things that happen, such as “data ready” or “DMA done.” For each pair of state and event, a table gives an action to run and the next state. If a pair has no row, nothing happens, and that is a decision you made, not an accident.
Valvano’s chapter 5 teaches machines as exactly this kind of table, and Elecia White’s book compares several ways to write them (switch statements, event-centric and table-driven). The table form wins for drivers because you can read the whole behaviour on one screen and test every row.
UNINIT: the chip has not been checked. IDLE: configured, waiting for a data-ready signal. READING: a DMA transfer is running, and the buffer belongs to the DMA. RECOVER: an error happened, and the driver is resetting the SPI. FAULT: too many failures, so the driver stops and reports. Each state answers one question, so a bug report can say, “it was stuck in RECOVER,” and everyone knows where to look.
Try the machine. Fire events from the chip and the bus, and watch the table pick a row.
The purple box is the current state. Press an event. The table highlights the row that fired. An event with no row is ignored and counted.
| State | Event | Action | Next |
|---|
A model of the driver’s control logic, with no bus underneath. The RECOVER row gives up after 3 failed recoveries (an illustrative limit). The state names are this lesson’s, not ST’s.
Trace a normal second of life by hand. The driver starts in UNINIT. INIT_OK moves it to IDLE. DRDY starts a DMA and moves it to READING. DMA_DONE pushes a sample and returns to IDLE. Then a cable glitch: in READING a TIMEOUT arrives, the driver aborts the SPI and goes to RECOVER with one retry counted. RESET_DONE returns it to IDLE, because 1 is less than 3. The flag bug cannot happen: leaving READING by any row ends the read, because there is no other way out.
Now the code. The table is data. One tiny function walks it.
ctypedef enum { S_UNINIT, S_IDLE, S_READING, S_RECOVER, S_FAULT } state_t; typedef enum { E_INIT_OK, E_BAD_ID, E_DRDY, E_DMA_DONE, E_DMA_ERR, E_TIMEOUT, E_RESET_DONE, E_RESET_CMD } event_t; typedef struct { state_t from; event_t ev; void (*act)(void); state_t to; } row_t; static const row_t TBL[] = { { S_UNINIT, E_INIT_OK, act_enable_drdy, S_IDLE }, { S_UNINIT, E_BAD_ID, act_report, S_FAULT }, { S_IDLE, E_DRDY, act_start_dma, S_READING }, { S_READING, E_DMA_DONE, act_push_sample, S_IDLE }, { S_READING, E_DMA_ERR, act_abort, S_RECOVER }, { S_READING, E_TIMEOUT, act_abort, S_RECOVER }, { S_READING, E_DRDY, act_count_miss, S_READING }, /* RECOVER and FAULT rows follow the same pattern */ }; static state_t g_state = S_UNINIT; void imu_dispatch(event_t ev) { /* called from the main loop, one event at a time */ for (unsigned i = 0; i < sizeof TBL / sizeof TBL[0]; i++) { if (TBL[i].from == g_state && TBL[i].ev == ev) { TBL[i].act(); g_state = TBL[i].to; return; } } g_ignored++; /* no row: a decision, and counted */ }
Events come from interrupts, but the dispatcher runs in the main loop. The ISR pushes an event code into a small queue, exactly like the sample queue in chapter 5. This keeps actions out of interrupt context and keeps the machine from being re-entered while it changes state. The rule is one event at a time, run to completion.
A switch on the state is just as correct, and short machines read well that way. The table pays off at about ten rows, when you want to print it, check it for missing rows, or generate a test for each row. It is also the form that a unit test can walk, which chapter 8 uses.
A table gives you a free review tool. Count the cells. Five states and eight events make 40 cells. The table has 9 rows, so 31 cells are blank. Walk the blank cells and ask of each one: should this be ignored, or did I forget it?
Some blanks are right. DMA_DONE in IDLE cannot happen, because no DMA is running. Others are bugs waiting. What if a TIMEOUT event arrives in IDLE because a late timer fired after the read had just finished? The table ignores it. That is correct, but you should decide it, and the g_ignored counter shows you if it happens often. A counter that climbs is a clue to a race.
Look at the RECOVER row. The event is the same, RESET_DONE, but the next state depends on a condition: fewer than 3 retries goes to IDLE, three or more goes to FAULT. A condition on a row is called a guard. Write guards as small functions that return true or false, and keep them free of side effects, so a test can call them alone.
Some work belongs to the state rather than to any one row. When the machine enters READING, it should always raise chip select and start the timeout timer. When it leaves, it should always stop the timer. Put this work in an entry action and an exit action for the state, so every row into READING does it without you repeating the code. This is how you avoid the old bug where one path forgot to stop the timer.
The timeout is itself an event. A one-shot timer, started on entry to READING and stopped on exit, pushes E_TIMEOUT into the event queue if it expires. The machine does not poll the clock. All the driver’s time-dependent behaviour is a row in the table.
The first is calling the dispatcher from inside an ISR. The ISR then runs an action, such as act_start_dma, while the main loop is halfway through a different row. The state variable changes under the main loop’s feet. The symptom is a state that is impossible to reach by reading the table. The fix is the rule from above: ISRs push events, and only the main loop dispatches.
The second is an action that sends an event to its own machine and expects it to run at once. If act_abort pushes E_RESET_DONE into the queue, the event waits for the next loop pass, and the machine sits in RECOVER until then. Treat the queue as a real delay of one pass, and design for it.
g_state, the retry count and g_ignored over the serial port. Then unplug the SPI MISO wire during a run. Confirm that the machine passes through READING, RECOVER, and FAULT after three recoveries, rather than hanging.DRDY event arrives. The table says: count a miss and stay in READING. Why is that better than starting another DMA?Chapter 8
Make the driver survive a short frame, a stuck bus and a wrong chip, and prove it with tests that need no board
A robot works for nine days. On day ten a connector warms up in the sun and the IMU stops answering for 40 ms. The driver from chapter 1 gets back the same bytes as the last good read, because its buffer still holds them. It reports a motionless robot. The balance loop believes it and drives the motors the wrong way.
That is a silent failure, and it is the worst kind. The symptom: values freeze while the robot moves. The measurement: on a logic analyzer the SPI lines show no activity from the chip, and the status the HAL returned was an error that the driver threw away. The fix: check every status, validate every length, bound every wait, and count every failure.
Check the status of every call. The HAL returns HAL_OK, HAL_ERROR, HAL_BUSY or HAL_TIMEOUT. Pass that up as your own error code. Never use the buffer after a failed call.
Validate what came back. Did you get the 6 bytes you asked for? Does WHO_AM_I equal 0x6C? A wrong ID at start-up means a wrong chip or a broken wire, and the driver should refuse to run.
Bound every wait. A timeout must be shorter than the time you can afford. At 1,667 Hz with an 8 slot queue you have 8 × 0.6 = 4.8 ms before samples are lost. A 2 ms timeout fits. HAL_MAX_DELAY does not.
Retry a bounded number of times, then stop. A transient glitch deserves one or two more tries. A dead chip does not deserve an endless loop. After three failures the state machine from chapter 7 enters FAULT and the application is told. Count every retry in a variable you can read out later.
You cannot unplug a cable on demand in a unit test. But you built the port in chapter 2, and the driver talks only to it. So you write a second port, a fake: a few lines of C that pretend to be the chip, with a switch to make them misbehave. The driver cannot tell the difference. Your laptop compiler builds both together, and the tests run in milliseconds. Testing firmware in depth is the subject of the testing lesson.
The device below does this in the page. It contains a real, tiny fake chip and two drivers written in JavaScript, mirroring the C. The naive driver is the one from chapter 1. The hardened driver follows the four rules. Six tests inject one fault each. Switch drivers and see which tests fail.
Pick a driver, then press Run. Each test makes the fake chip fail in one way and checks what the driver does.
The fake chip, the drivers and the tests are real code running in this page, but the drivers are JavaScript ports of the C idea, and the faults are the six this lesson chose. They show the method, not a complete test suite.
The naive driver fails five tests. For a bus error it returns the old buffer, about 1 mg on each axis, as if it were a fresh reading. For the stuck bus it spins 1,000 times and, in real firmware, forever. These are exactly the day-ten failures. The hardened driver turns each of them into a return code the state machine can act on.
c/* the same test in C, against a fake port. Build with the host gcc: no board, no HAL. */ static int fault; /* 0 none, 1 bus error, 2 short frame ... */ static int32_t fake_read(void *h, uint8_t reg, uint8_t *buf, uint16_t len) { if (fault == 1) return -1; /* the bus failed */ if (reg == 0x0F) { buf[0] = 0x6C; return 0; } static const uint8_t acc[6] = { 0xAF, 0x07, 0xCC, 0xFC, 0x66, 0x3F }; memcpy(buf, acc, len); return 0; } void test_bus_error_is_reported(void) { fault = 1; float mg[3]; ASSERT(imu_read_accel_mg(mg) != 0); /* must fail loudly */ }
A fake is not a mock. A mock checks that certain calls happened in order. A fake behaves like the real thing, so the same fake serves many tests and survives refactors of the driver.
One honest limit: a fake only knows the faults you imagined. It cannot find the chip’s undocumented quirk or a timing problem at the real clock. Tests on the board still matter. The fake catches the cheap bugs early, and the board catches the strange ones late.
A hardened driver retries three times with a 2 ms timeout. Do the sum: 3 × 2 ms = 6 ms of blocking in the worst case. The queue from chapter 5 gave us 4.8 ms before samples are lost at 1,667 Hz with 8 slots. The retry loop alone is over budget. The “hardened” driver now causes the failure it was written to prevent.
There are two fixes. Shorten the timeout so that tries times timeout fits: 3 × 1 ms = 3 ms fits inside 4.8 ms. Or, better, do not retry inside the call at all. Return the error at once, let the state machine move to RECOVER, and retry on the next data-ready event. That keeps every pass short and moves the policy into a table row you can see and test. The device in this chapter retries in a short loop because the fake port answers instantly. A real driver on a real bus should use the second form.
A fault that the driver survives should still leave a mark. Keep a small struct of counters: reads attempted, reads failed, retries, timeouts, samples dropped, events ignored. Send it with the telemetry or print it on request. A healthy unit shows zeros. A unit with a loose connector shows a rising retry count days before it fails outright.
Latch the first error, too. Store the state, the event and the error code at the moment of the first failure. By the time a person looks, later errors have buried it. The first one is usually the cause.
The last line of defence is a hardware watchdog, a timer that resets the chip unless the main loop feeds it regularly. Feed it only from the point in the loop where all jobs ran, never from an ISR, so a stuck loop cannot hide behind a working interrupt. The bigger safety picture is the subject of fail-safe design.
The six tests in the device inject one fault each. Real failures arrive in combinations: a short frame during a retry, a timeout while the queue is full. Add tests that chain two faults. Add a test that runs the state machine through every row once, and another that fires every event into every state and checks that no state is left unreachable. These cost minutes to write and run in milliseconds on a laptop. A test that fails on your desk is cheaper than a unit that fails in a field.
Chapter 9
Keep the numbers, the checklist and the core code, and see where this lesson sits in the series
A driver keeps a promise about one device. It splits chip knowledge from board knowledge with a small port struct. It reads in one of three styles: block, interrupt per byte, or DMA. It starts reads when the chip says data is ready, passes samples through a queue, and runs in a loop that never waits. A table-driven state machine tracks what the driver is waiting for. Every call is checked, every wait is bounded, and a fake port lets you test all of it on a laptop.
| What | Value | Where it comes from |
|---|---|---|
| LSM6DSO identity | WHO_AM_I at 0x0F reads 0x6C | ST lsm6dso-pid driver header |
| Rate and range setting | CTRL1_XL at 0x10; rate in the top nibble (104 Hz is code 4, so 0x40) | ST driver header |
| Result registers | OUTX_L_G 0x22 (gyro), OUTX_L_A 0x28 (accel), low byte first | ST driver header |
| Data-ready flags | STATUS_REG 0x1E: XLDA bit 0, GDA bit 1; INT1_CTRL 0x0D bit 0 puts accel data-ready on INT1 | ST driver header |
| Auto-increment | IF_INC bit in CTRL3_C at 0x12 steps the address in a burst | ST driver header |
| Scale at the three ranges | 0.061, 0.122, 0.244 mg per count (±2, ±4, ±8 g) | ST driver source |
| HAL SPI states | READY = 1, BUSY_TX_RX = 5, ERROR = 6 | STM32F4 HAL header |
| 13 byte frame at 6.25 MHz | 104 clocks, 16.64 µs | Arithmetic (clock illustrative) |
| CPU load at 6,667 Hz, 12 byte burst | blocking 11.8%, interrupt per byte 14.3%, DMA 3.3% | The lesson’s model, toy costs |
| Queue for a 5 ms stall at 600 µs samples | 8.3 samples, so 9 slots | Arithmetic |
| Term | Meaning in one line |
|---|---|
| Register map | The chip’s table of numbered one-byte settings and results. |
| Port | The thin file that connects a driver to one board’s HAL, pins and delays. |
| HAL | A vendor layer that hides one chip family’s peripherals behind common calls. |
| Blocking, interrupt, DMA | Wait for the bus; get called back per byte; let an engine copy and call back once. |
| Data-ready | The chip’s signal that a new sample waits. |
| Ring buffer | A fixed array used in a circle, with one writer for each index. |
| Run to completion | A job finishes its piece before the next job starts. |
| State, event, action | What the driver waits for; what happened; what it does about it. |
| Fake | A stand-in port that behaves like the chip and can be made to fail. |
c/* imu.c: the whole driver in outline. Port, queue, ISR hooks, state machine. */ typedef struct { int32_t (*read)(void*, uint8_t, uint8_t*, uint16_t); int32_t (*write)(void*, uint8_t, const uint8_t*, uint16_t); int32_t (*start_dma)(void*, uint8_t*, uint8_t*, uint16_t); void *h; } imu_port_t; /* the board's side of the promise */ int imu_init(const imu_port_t *p) { uint8_t id; if (p->read(p->h, 0x0F, &id, 1) || id != 0x6C) return -2; uint8_t rate = 0x40, drdy = 0x01; /* 104 Hz; INT1 data-ready */ p->write(p->h, 0x10, &rate, 1); p->write(p->h, 0x0D, &drdy, 1); imu_dispatch(E_INIT_OK); return 0; } void imu_on_int1(void) { evq_push(E_DRDY); } /* EXTI ISR: push, nothing else */ void imu_on_dma_done(void) { cs_high(); evq_push(E_DMA_DONE); } /* DMA callback */ void imu_poll(void) { event_t e; while (evq_pop(&e)) imu_dispatch(e); check_timeout(); } /* main loop, every pass */
This lesson is the middle of the foundation spine. Behind it: buses on the wire for the SPI frame, timers and sampling for sample times, reset to main() for how the code starts, and the pipeline and privilege levels for what an interrupt does to the core. Ahead: where memory goes (the buffers of chapter 4), testing firmware (chapter 8 in depth), Zephyr (a framework that ships drivers, queues and a sensor API), and embedded Rust (the same driver where the compiler checks ownership of the bus). An RTOS replaces the super loop; see the RTOS survey and real-time systems. For wiring and the board view, see hardware interfacing. Robot-level integration lives in sensor and actuator integration and real-time performance. A DRDY-driven ADC driver for a biopotential chip uses this exact pattern in acquisition firmware.
lsm6dso_reg.h and .c): register addresses, bit fields, the stmdev_ctx_t port struct and the scale factors.stm32f4xx_hal_spi.h: the blocking, interrupt and DMA SPI calls, the completion callback and the state values.Now press Present or Teach and explain one IMU sample from the pin to the application, from memory: the data-ready signal, the DMA, the queue, the loop and the state table. Then go back to the three timelines at the top, set 6,667 Hz and a 120 byte burst, and explain why every style struggles and which one fails first.