Take a blank STM32 chip to a battery sensor node that must pass six tests: fast response, one year on a cell, a power cut, an update, injected faults and a hang.
Build every layer of a small firmware product, from the first clock to the last test, and see which layer each test needs.
Press Ship-ready, then Blank firmware. Now switch the layers on one at a time and watch which of the six tests turns green. Then we build each layer, piece by piece, and measure it.
You need a little C and a feel for what a microcontroller is: a tiny computer on one chip. We build the rest from zero.
A capstone for the Firmware from Zero to Expertise series. It follows the shape of the capstone projects in CMU 18-349 Introduction to Embedded Systems and chapter 10 of Valvano and Yerraballi, Embedded Systems: Shape the World. Numbers come from the STM32L476 datasheet. Everything here is a model, not real silicon.
A model, not silicon. Anchors from the STM32L476 datasheet: 100 and 131 microamps per MHz in Run, 1.4 microamps in Stop 2 with the RTC, 22.02 ms to erase a 2 KB page, 81.69 microseconds to program 64 bits, a 32.768 s longest watchdog timeout. Radio, sensor and software costs are illustrative; chapters 1 to 9 show each formula.
Chapter 0
See why a product is a list of promises, and why every promise reaches down through several layers of code
A customer hands you a small board and says: “Put fifty of these in a cold store. Each one measures vibration, sends a summary every second, and must run for a year on one battery.” The chip on the board has never run a line of your code. Its flash memory (the storage that keeps your program when the power is off) is empty.
You have a year of lessons behind you. You know what a register is, how a clock tree works, how a bus carries bytes and how an interrupt steals the CPU for a moment. This lesson asks a harder question. Can you put all of it together so that the product keeps its promises when nobody is watching?
A wish like “it must be reliable” cannot be checked. Valvano and Yerraballi start their design chapter with a requirements document: a short text that says what the system will do, in an overview, a function description and a list of deliverables. Each line must be something you can measure. We follow the same habit, and turn each wish into a test: a fixed procedure with one number and one limit.
Our node has six tests, and the customer will run all of them before accepting the order.
The 5 ms, the 91 microamps and the 5 s are the limits of this lesson. They are illustrative choices, picked so that each test has a real design trade behind it. The customer in your own project picks the real ones.
Here is the lesson of the whole capstone. No test belongs to one piece of code. The latency test looks like a driver problem, but it also needs the right clock speed, an interrupt that starts the read, and a task that is allowed to run at once. The battery test looks like a sleep problem, but it also needs the bus read to wait in a low-power state, and the radio to share the CPU politely.
So we build the node in layers, in the order a real project does it. We call each layer a module, as Valvano does: a piece with a clear interface that you can test alone before you join it to the rest.
Try the map below. It shows which layers each test needs. Build the layers in order and watch the tests light up.
Each row is a layer. Each column is a test. A dot means the test needs that layer. Drag to build more layers. A test lights up when every layer it needs exists.
The dependency map is this lesson’s own design for this node, not a standard. A real product has its own map. The point is that every column needs several rows.
Look at the OTA column. It needs the storage layer, and it also needs the watchdog layer. That is not a typo. When a new firmware image hangs on its first boot, only a watchdog can force the reset that lets the bootloader roll back. Chapter 7 shows this in detail.
Real firmware runs on real silicon, and a browser cannot run it. So every device in this lesson is an honest model: a small program that follows the same arithmetic as the chip, with numbers from the STM32L476 datasheet where we have them. We call the part STM32L476RG, an ultra-low-power Arm Cortex-M4 chip that sits on the Nucleo-L476RG board. Each chapter ends its device with an On real hardware note. It names the board and the measurement to repeat, so you can check our model against the truth.
One rule runs through the whole lesson: measure, then change. Many hours of firmware work go into the wrong layer because the engineer guessed. You will see our own guess fail in Chapter 5.
Chapter 1
Bring the chip to life, pick a clock speed, and see that going faster changes time much more than it changes energy
You plug in the board and load your first program: blink one LED. Nothing blinks. The code looks right. The chip is running, but a part of it is still switched off, and your program is talking to a wall.
This is the most common first failure in firmware, and it has one cause. A microcontroller saves power by keeping everything off until you ask for it. Before a peripheral (a block of hardware, such as a pin driver or a bus) does anything, you must give it a clock and set it up. Bring-up is the work of doing that in the right order. The first-light lesson shows it step by step. Here we need only the idea, because the capstone needs one decision from it: how fast should this node run?
The clock is a square wave that makes the CPU take one step on every tick. One tick is one cycle. A chip at 4 MHz takes four million cycles a second. A small piece of software, say one pass of a filter, needs a fixed number of cycles. We guess 1,500 cycles for one sensor sample, and measure the real number in Chapter 9.
After a reset, and after waking from the deepest sleeps, the STM32L476 starts on an internal oscillator called MSI at 4 MHz. It needs no parts on the board and starts in microseconds. The chip can also use HSI16, an internal 16 MHz oscillator, and a PLL (phase-locked loop), which multiplies a slow clock up to the 80 MHz maximum. The PLL needs time to lock, so it is slow to start.
The datasheet gives the price of speed as current per megahertz. The headline figure is 100 microamps per MHz in Run mode. Table 30 lists measured values: about 100 microamps per MHz for runs up to 26 MHz, and 131 microamps per MHz (10.5 mA in total) at 80 MHz.
Now an easy mistake. “A faster clock burns more current, so the node should run slowly.” Current is not the right thing to count. A job needs a fixed number of cycles. At a faster clock it finishes sooner, and the chip can sleep for the rest of the time. What the battery pays is charge: current multiplied by time, in microcoulombs (µC).
Work it for one batch of 16 samples, which is 16 × 1,500 = 24,000 cycles:
The charge is the same at 4 and 16 MHz, because the current per MHz is the same. It is 31 percent higher at 80 MHz, because the chip needs more current per MHz there. Speed bought us a 20 times faster job for a 31 percent charge penalty. If the CPU then sleeps in Stop 2, it pays almost nothing for the time it saved.
There is one more cost, and it hides in the wake-up. Each time the node wakes from Stop 2, the clock must start again. The datasheet (Table 40) gives 10.6 µs to reach Run mode with the 4 MHz MSI and 7.3 µs with HSI16. An 80 MHz PLL adds its lock time on top; we guess 40 µs. With a wake-up 6.25 times a second, that extra 40 µs costs about 3 µA at 10.5 mA. This is small, but our whole budget is 91 µA.
The three bars show one batch of 16 samples. Time is how long the CPU is busy. Charge is current times time. Wake cost is the clock start-up, six times a second. Choose a speed and compare.
Illustrative software cost of 1,500 cycles per sample. Current per MHz is from datasheet Table 30 (100 µA up to 26 MHz, 131 µA at 80 MHz). Wake times are from Table 40 (10.6 µs with MSI 4 MHz, 7.3 µs with HSI16); the PLL lock time of 40 µs is a guess. The time bar includes the bus read of Chapter 2 only in the latency test, not here.
On real hardware: Nucleo-L476RG. Set one GPIO high at the start of the batch and low at the end. Measure the pulse width on a scope at 4, 16 and 80 MHz. Then read the current of the chip with a meter on the board’s current-measurement jumper (see your board’s user manual), and multiply. Your charge numbers should be near ours. If they are not, your software cost is not 1,500 cycles per sample.
This is the whole of first light for our node. It turns on HSI16, waits until it is ready, switches the system clock to it, and gives the LED pin a clock and an output mode. Notice the two waiting loops. A register write does not take effect instantly; you must read a ready flag.
c/* STM32L476RG, CMSIS names. Nucleo LD2 is on PA5. */ void clock_init_16mhz(void) { RCC->CR |= RCC_CR_HSION; /* start the 16 MHz internal oscillator */ while (!(RCC->CR & RCC_CR_HSIRDY)) {} /* wait until it is stable */ /* if the reference manual's table asks for flash wait states at this speed, set them here, BEFORE the switch */ RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_CFGR_SW_HSI; /* choose HSI16 as the system clock */ while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSI) {} /* wait until the switch is real */ } void led_init(void) { RCC->AHB2ENR |= RCC_AHB2ENR_GPIOAEN; /* the step people forget: clock the port */ GPIOA->MODER = (GPIOA->MODER & ~(3u << (5 * 2))) | (1u << (5 * 2)); /* PA5 = output */ } void led_toggle(void) { GPIOA->ODR ^= (1u << 5); }
The failure mode from the opening is one line: the missing AHB2ENR write. The symptom is an LED that stays dark. The measurement is a read of GPIOA->MODER in the debugger: it still holds its reset value, because a write to an unclocked port is ignored. The fix is that one line, placed before any other GPIO access.
For the capstone we choose 16 MHz from HSI16. It is fast enough for the 5 ms latency limit (Chapter 3 shows why), it needs no PLL, it wakes fastest, and its charge per job equals that of 4 MHz.
Chapter 2
Read six bytes from a sensor over I2C, count every bit-time on the wire, and turn the bytes into a number you can trust
The chip now runs at 16 MHz. Next to it sits the reason the node exists: a small accelerometer that feels vibration. Your code must ask it for a reading. That asking is the driver: the code that knows how to talk to one particular part, and hides that knowledge from the rest of the program.
We use a virtual sensor called VS-1. Its registers are invented for this lesson, but its habits are real: sixteen-bit words, low byte first, and a burst read that walks through the registers one after another. The datasheet lesson shows how to find these facts on a real part.
Four facts are enough. VS-1 sits on the I2C bus at the 7-bit address 0x19. Its acceleration data starts at register 0x28 and runs for six bytes: X low, X high, Y low, Y high, Z low, Z high. Each axis is a signed 16-bit number. The full scale is plus or minus 4 g, so one step of the number is 4,000 mg divided by 32,768, which is 0.122 mg.
I2C is a two-wire bus. One wire, SCL, carries the clock. The other, SDA, carries the data. The chip that starts a talk is the controller (our STM32). The chip that answers is the target (VS-1). The bus has two speeds you will meet most: Standard-mode at 100 kHz and Fast-mode at 400 kHz, both from the I2C specification (NXP UM10204).
To read six bytes, the controller speaks in this order. Every byte is eight bits, followed by a ninth clock for the ACK: the receiver pulls SDA low to say “got it”, or leaves it high for a NACK, “no”.
Count the clocks. Three bytes of setup take 3 × 9 = 27 clocks. Six data bytes take 6 × 9 = 54. The START, repeated START and STOP take about one bit-time each, so 3. The total is 84 bit-times. At 400 kHz a bit-time is 2.5 µs, so the read takes 84 × 2.5 = 210 µs. At 100 kHz it takes 840 µs. In general, a read of n bytes takes 30 + 9n bit-times. Try it.
Top: the fields of the read. Middle: SCL, the clock. Bottom: SDA, the data. Pick a speed and a byte count. Then switch on the wrong address and see what the bus does.
A modelled trace drawn from the frame rules above, not a capture. The bytes are made-up sample data. Real traces also show rise times and clock stretching, which this model leaves out. Bus timing per the I2C-bus specification UM10204.
On real hardware: Nucleo-L476RG. Wire a real I2C sensor board to the I2C1 pins and clip a logic analyzer on SCL and SDA. Capture one read at 100 kHz and at 400 kHz. Measure the time from START to STOP. It should match 30 + 9n bit-times, and any extra time is the controller idling between bytes.
The bus delivers bytes. Your program wants milli-g. Here is a worked read. VS-1 sends 0x34, 0x12, 0xF0, 0xFF, 0x10, 0x27.
Two details bite beginners. First, the order of bytes (endianness) is a choice the chip maker made. VS-1 puts the low byte first. Second, the sign. If you store the joined word in an unsigned variable, Y becomes 65,520 instead of −16, and a quiet sensor looks like a violent shake.
c/* VS-1 driver, STM32 HAL. Registers are the virtual sensor's. */ #define VS1_ADDR (0x19 << 1) /* HAL wants the 7-bit address shifted left by one */ #define VS1_DATA 0x28 typedef struct { int16_t x, y, z; } vs1_raw_t; int vs1_read(vs1_raw_t *out) { uint8_t b[6]; if (HAL_I2C_Mem_Read(&hi2c1, VS1_ADDR, VS1_DATA, I2C_MEMADD_SIZE_8BIT, b, 6, 2) != HAL_OK) return -1; /* NACK or 2 ms timeout: tell the caller */ out->x = (int16_t)(b[0] | (b[1] << 8)); /* low byte first, then cast to SIGNED */ out->y = (int16_t)(b[2] | (b[3] << 8)); out->z = (int16_t)(b[4] | (b[5] << 8)); return 0; } static inline int32_t raw_to_mg(int16_t r) { return ((int32_t)r * 4000) / 32768; }
A driver is easy to get almost right. Suppose your values are all 0xFF, which is a reading of −1 on every axis, however hard you shake the board. That is the symptom. The measurement is a logic analyzer on the bus: the ninth clock of the first byte shows SDA high, a NACK. Nobody answered. When no chip drives the bus, pull-up resistors hold SDA high, and a read of an empty bus returns all ones. The fix in the common case is the address: the HAL wants 0x32, and your code passed 0x19. Turn on “Wrong address” in the device above and watch the frame end after ten bit-times.
Look again at the code. The function returns −1 when the read fails. The caller must check it. A driver that hides errors teaches the rest of the system to trust garbage, and Chapter 8 pays for it.
Chapter 3
Stop asking the sensor for data, let it tell you when data is ready, and let a copy engine move the bytes
Your driver works. It reads one sample, converts it and waits for the next. The sensor makes a sample every 10 ms, and your main loop asks for it each time. Between questions the CPU runs a tight loop that checks a flag. Nothing wrong shows on the screen. But the battery test lights red.
This style is called polling: you keep asking, “are you ready yet?” It is like checking the oven every ten seconds. You never relax, and the CPU never sleeps. The cure has two parts, and both reach into hardware that the interrupts and DMA lesson explains in full. We take only what the capstone needs.
An interrupt is a signal that makes the CPU stop its work, run a short piece of code called the interrupt service routine (ISR), and then go back. The sensor has a pin for it. When data is ready, the sensor pulls the pin, and the chip wakes up.
The Cortex-M4 reacts fast. Arm documents an interrupt latency of 12 cycles with zero wait-state memory: the time from the signal to the first instruction of the ISR. At 16 MHz that is 12 ÷ 16 = 0.75 µs. This is only the hardware part. Flash wait states and your own code add to it.
The sensor also helps with a trick: a FIFO (first in, first out queue) inside the sensor chip. VS-1 stores each sample there. You set a watermark, a count at which it raises the interrupt. With a watermark of 16 samples, the interrupt fires 6.25 times a second instead of 100.
Even with a FIFO, somebody must move 96 bytes (16 samples of 6 bytes) off the bus. That takes 30 + 9 × 96 = 894 bit-times, which is 2.2 ms at 400 kHz. If the CPU does it, the CPU spins for 2.2 ms. DMA moves bytes between a peripheral and memory by itself. You give it a source, a destination and a count. The CPU can then go to Sleep mode, where the CPU clock stops but the bus keeps working. Table 31 of the datasheet gives the price: 0.61 mA at 16 MHz, against 1.6 mA when running.
Let us add up one second, with the clock at 16 MHz and Stop 2 between jobs. Each CPU-awake microsecond costs 1.6 mA, and a wake-up from Stop 2 takes 7.3 µs (Table 40).
Moving from A to C halves the cost of the node’s own work. But look at a second number, which is the latency. The path from the interrupt to a handled batch is wake 7.3 µs, ISR entry 0.75 µs, bus 2,235 µs and processing 1,500 µs: 3.74 ms. That fits the 5 ms limit. Design A has a different latency problem, which Chapter 4 explains: its main loop also waits 8 ms for the radio.
Each row is a design. The bar shows how long per second the CPU is working: blue is waiting on the bus, orange is software. Choose a design, then drag the FIFO watermark. A bigger batch saves wake-ups, but it makes the answer come later.
Model at 16 MHz with Stop 2 between jobs. Datasheet: Run 100 µA/MHz (1.6 mA), Sleep 0.61 mA at 16 MHz (Table 31), Stop 2 wake 7.3 µs (Table 40). The 1,500 cycles per sample, the 2 ms radio burst and 4.4 µA of always-on parts are illustrative. Arm documents 12 cycles of interrupt latency for the Cortex-M4.
On real hardware: Nucleo-L476RG. Toggle one GPIO pin at the first line of the ISR and another when processing ends. Put both on a scope with the sensor’s interrupt pin. The gap between the sensor pin and the first GPIO edge is your true interrupt latency, with your flash wait states and any competing interrupts included.
An ISR must be short. It should do only what cannot wait, and then hand the rest to a task. Ours starts the DMA read. When the read ends, a second callback wakes the sensor task.
cstatic uint8_t fifo_buf[16 * 6]; /* 96 bytes: 16 samples x 6 bytes */ extern TaskHandle_t sensor_task; void HAL_GPIO_EXTI_Callback(uint16_t pin) { /* runs in the sensor's interrupt */ if (pin == VS1_INT_PIN) HAL_I2C_Mem_Read_DMA(&hi2c1, VS1_ADDR, VS1_FIFO, I2C_MEMADD_SIZE_8BIT, fifo_buf, sizeof fifo_buf); /* start the copy; return at once */ } void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *h) { /* DMA finished */ BaseType_t woken = pdFALSE; vTaskNotifyGiveFromISR(sensor_task, &woken); /* tell the task: data is in fifo_buf */ portYIELD_FROM_ISR(woken); /* run it now if it is the most urgent task */ }
The failure to fear here is the long ISR. Suppose you decide to process the 16 samples inside the callback. The symptom is odd: a button press is sometimes missed and a UART drops a byte, although neither code path changed. The measurement is the two-GPIO trick above: the ISR pulse is 1.5 ms wide, and every other interrupt of the same or lower priority waits for it. The fix is the code above. The ISR starts the work and notifies a task. The task, which can be interrupted, does the 1.5 ms of processing.
Chapter 4
Split the firmware into jobs with priorities, and measure how long the most urgent one waits when a slow job is already running
The node now has a second job. Once a second it packs the latest summary and sends it by radio. The radio module is slow. Your code writes the packet, then waits in a loop for the module’s ready flag. That wait can last 8 ms.
Picture the main loop at the moment the sensor raises its interrupt. The loop is inside the radio wait. The DMA read can start, because that is hardware. But the processing code is back in the main loop, behind the radio wait. The batch sits unhandled for up to 8 ms. The limit is 5 ms. The test fails at its worst case, and it will fail only now and then, which is the hardest way to fail.
A task is one job with its own stack (its private scratch memory) and its own place in the code. A scheduler is the small piece of the operating system that decides which task owns the CPU. Each task has a priority, a number. The rule of a preemptive scheduler is simple: whenever a higher-priority task becomes ready, it takes the CPU at once, and the lower task pauses where it is.
We make three tasks, using FreeRTOS, a widely used small RTOS. The RTOS survey and the RTOS internals lesson cover how a context switch works.
Now the same moment as before. The radio task is 3 ms into its 8 ms wait when the interrupt fires. The ISR notifies the sensor task and asks to yield. The sensor task has priority 3, the radio task priority 2, so the scheduler switches at once. The sensor task takes the CPU, reads and processes for 3.74 ms, and goes back to sleep. Then the radio task resumes its wait. The latency is 3.74 ms, whatever the radio is doing.
Reverse the priorities and the picture flips. The radio task keeps the CPU for its remaining 5 ms. The sensor task starts at t = 8 ms, and it ends at 11.74 ms. The latency from the interrupt (at t = 3 ms) is 8.74 ms. Try this in the device.
Orange and blue make the sensor task: first the bus read, then the processing. Pink is the radio task. Choose which task has the higher priority, then drag the moment the sensor interrupt arrives.
Model at 16 MHz: bus read 2.235 ms and processing 1.5 ms for 16 samples, a radio wait of 8 ms (illustrative), context switch time left out because it is small next to the milliseconds shown; measure yours. The tick cost is 1,000 wake-ups from Stop 2 per second at 7.3 µs and 1.6 mA each (datasheet Tables 30 and 40).
On real hardware: Nucleo-L476RG. Put one GPIO high while the sensor task runs and another while the radio task runs. Run for ten minutes with a scope in persistence mode, triggered on the sensor interrupt pin. The worst gap between the trigger and the sensor pulse is your real worst-case latency. A tracing tool such as SEGGER SystemView gives the same picture without wires.
An RTOS keeps time with a tick: a timer interrupt, usually every millisecond. The tick lets the scheduler wake tasks that called vTaskDelay. But a tick every millisecond means the CPU leaves sleep a thousand times a second, just to find out that nothing needs doing.
Count it. Each wake from Stop 2 takes 7.3 µs with HSI16 (datasheet Table 40) at about 1.6 mA. One thousand wake-ups cost 1,000 × 7.3 µs × 1.6 mA = 11.7 µC per second, which is 11.7 µA. Our whole budget is 91 µA, and this is wasted.
The cure is tickless idle. When only the idle task is ready, the kernel works out how long until the next task must wake, stops the tick, sleeps for exactly that long, and then corrects its tick count when it wakes. In FreeRTOS you set configUSE_TICKLESS_IDLE to 1 for the built-in version, or to 2 when you supply your own. The kernel only tries it if the expected idle time is at least configEXPECTED_IDLE_TIME_BEFORE_SLEEP ticks, which defaults to 2.
For our node you need the value 2. The built-in Cortex-M version uses SysTick, which counts CPU clocks. In Stop 2 the CPU clock stops, and so does SysTick. The FreeRTOS documentation says that when SysTick is not the tick source you must define the hook yourself. In practice this means a low-power timer or the RTC does the waking, and your hook programs it with the idle time.
c/* FreeRTOSConfig.h (excerpt) */ #define configUSE_PREEMPTION 1 #define configMAX_PRIORITIES 5 #define configUSE_TICKLESS_IDLE 2 /* we supply portSUPPRESS_TICKS_AND_SLEEP (LPTIM or RTC wake) */ #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 /* default: do not bother for less than 2 ticks */ /* main.c */ xTaskCreate(sensor_task, "sensor", 256, NULL, 3, &sensor_task); /* most urgent */ xTaskCreate(radio_task, "radio", 384, NULL, 2, NULL); static void sensor_task(void *arg) { for (;;) { ulTaskNotifyTake(pdTRUE, portMAX_DELAY); /* sleep until the DMA callback gives us a notification */ process_batch(fifo_buf, 16, &summary); /* about 1.5 ms at 16 MHz */ xQueueSend(report_q, &summary, 0); /* hand the result to the radio task */ } }
Two traps wait here. The first is priority inversion: a high-priority task waits for a lock that a low-priority task holds, and a medium task keeps the low one from running. FreeRTOS mutexes use priority inheritance to soften this, but the safest design shares data through queues and notifications, as above. The second is a task that never blocks. If the sensor task spun in a loop instead of waiting for a notification, the idle task would never run, the sleep would never happen, and the battery test would fail with no visible error.
Chapter 5
Add up where the charge goes in a single second, and learn why you must measure before you decide what to fix
The prototype has been on the shelf for three weeks. You come back and the board is dead. The battery was a 1,000 mAh cell. A little arithmetic shows the node drew about 20 times the current it should have. Where did the charge go?
You cannot answer by staring at the code. You answer by keeping accounts. This chapter shows how, and the sleep and battery lesson goes deeper on the hardware side.
A battery stores charge, measured in milliamp-hours (mAh). A current of 1 mA drawn for 1 hour uses 1 mAh. A year has 8,760 hours. So the current the node may draw on average, for one year, is the charge divided by 8,760 hours.
A real cell does not give all of its rated charge. Cold weather, pulses of current and self-discharge all take a share. We keep 20 percent as a margin and call 80 percent usable. This is a lesson choice; a real project reads the cell’s data sheet. Then:
1,000 mAh × 0.8 = 800 mAh ÷ 8,760 h = 0.0913 mA = 91.3 µA
That 91.3 µA is the budget for the sum of everything: the CPU, the bus, the sensor, the radio and every leak.
Our node is mostly asleep. In Stop 2, the deepest sleep that still keeps the RAM and the RTC (real-time clock) running, the datasheet says the STM32L476 draws 1.1 µA, or 1.4 µA with the RTC. (Table 35 shows 1.18 µA at 3 V and 25 °C for the version without the RTC.) That is a thousand times less than running at 16 MHz.
When a job runs, the current jumps for a short time and falls again. The average current is the sum of each piece’s current times the fraction of the time it lasts. Equivalent, and easier: add the charge of each piece in one second. A charge of 1 µC per second is an average current of 1 µA.
The accounts for one second of the shipped design (16 MHz, Stop 2, FIFO of 16, DMA) are:
The total is 44.0 µA. The cell lasts 800 mAh ÷ 0.044 mA = 18,182 hours, which is 2.07 years. The node passes the battery test with a margin of about two. Now the blank firmware: the CPU never sleeps, so it draws 0.4 mA at 4 MHz plus the radio and the sensor, which is 419 µA. The cell lasts 1,909 hours, or 80 days.
The bar is the average current of the node. The pink line is the budget for one year. Switch the layers on and off. Slide the report period. Then add a floating pin and watch the budget break.
Same model as the hero. Datasheet anchors: Run 100 to 131 µA/MHz, Sleep 0.61 mA at 16 MHz, Stop 2 with RTC 1.4 µA, wake 7.3 or 10.6 µs. Illustrative: a 2 ms radio burst at 8 mA per report, a 2 µA sensor, 1 µA for the radio asleep, a 1,000 mAh cell with 80 percent usable. The floating pin models a 10 kΩ pull-up held low from 3.0 V: 300 µA.
On real hardware: Nucleo-L476RG. Measure the current of the chip with a power profiler or a source-meter on the board’s current-measurement jumper, at a sample rate fast enough to see the 2 ms radio burst. Remove the debugger’s link and any LED first, because they add current of their own. Integrate the trace over 60 seconds and divide by 60. Compare with the stacked bar.
Try to guess which piece is biggest. Most engineers say the CPU. In the shipped design the radio burst is the largest single item at 16 µA, more than a third of the total. Halving the CPU work would save under 8 µA. Sending a report every 2 s instead of every 1 s saves 8 µA with a one-line change. The profile tells you where to dig. This is why the rule of the lesson is “measure, then change”.
Two levers deserve names. Race to sleep means finishing a job fast so the chip can return to the cheapest state sooner. Chapter 1 showed its limits: if current per MHz is constant, speed alone does not change the charge. Batching means doing the work of many events in one wake-up, which is what the FIFO did.
Now the three-week story. The symptom is an empty cell. The measurement: a power profiler shows the floor between bursts at about 304 µA instead of 4.4 µA. The code sleeps correctly. The cause is the hardware: the powered-down sensor holds one pin low, while a 10 kΩ pull-up on the board still ties that pin to 3.0 V. The pull-up passes 3.0 V ÷ 10,000 Ω = 300 µA. The fix is firmware: before sleeping, change the pin so that nothing drives it against the pull-up, for example switch off the pull-up or make the pin an analog input. Switch on “Floating pin” in the device and read the new life of the cell.
Chapter 6
Learn how flash really changes, and store a record so that no instant of power loss can destroy it
Once an hour the node saves a small record: its calibration offsets and a counter. Last Tuesday a worker in the cold store knocked the battery contact at the wrong moment. The node restarted, read its record, and found rubbish. It sent nonsense for a week.
The code that saved the record looked right. It only had one bad property: it was not safe against power loss. The flash lesson covers the physics and file systems. Here we take the rule that matters for the capstone.
Flash is memory that keeps its bits without power. It has an odd rule. You can only change bits in one direction when you write: from 1 to 0. To get 1s back you must erase, and an erase works on a whole page. On the STM32L476 a page is 2 KB, and an erased page reads as all 1s (0xFF in every byte).
The datasheet gives the times (Table 50). Erasing one 2 KB page takes 22.02 ms typically and up to 24.47 ms. Programming 64 bits takes 81.69 µs, so a 256-byte record (32 words of 64 bits) takes about 2.61 ms. The chip draws about 3.4 mA during both. Table 51 guarantees at least 10,000 erase cycles per page.
Now see why a plain overwrite is dangerous. To change a record in place, you must first erase its page (22.02 ms) and then program the new record (2.61 ms). For 24.63 ms the page holds no valid record at all. If the power fails at any point in that window, the old record is gone, and the new record is missing or half-written.
The cure is a rule you will meet in every safe storage system: never destroy the old copy until the new copy is complete. We make that concrete with a journal, which is a log of records written one after another. Each record is 256 bytes and carries:
A 2 KB page holds 8 records. To save, we program the next empty slot. We do not erase anything. To read at boot, we scan every slot and keep the record with a valid CRC and the highest sequence number. When a power cut hits during programming, that slot has a bad CRC, and the scan simply picks the record before it. The CRC acts as the commit: a record exists only when its last byte is right.
When the page is full, we use a second page. We erase the other page, then write the new record at its start. The full page, with the latest good record in it, stays untouched until the new page holds a valid record. Even a cut in the middle of the erase leaves the old page whole.
Wear works out well. Each page is erased once per 8 records, and the two pages alternate, so one erase serves 16 saves per pair. At one save an hour, in-place overwriting reaches 10,000 erase cycles after 10,000 hours: 1.1 years. The journal reaches it after 10,000 × 16 = 160,000 saves, which is 18.3 years. The same design gives both safety and a longer life.
The bar is the time of one save. Drag the cut. The two chips show what the flash holds afterwards. Press Cut at every instant to test 246 cuts, one every 0.1 ms.
Timings from datasheet Table 50: page erase 22.02 ms typical, 256-byte record 2.61 ms (32 words of 81.69 µs each). A real half-erased page can also read back as unstable bits; the journal never touches the page that holds the live record while it erases the other one. In the journal view the old page was full, so the save also erases the other page.
On real hardware: Nucleo-L476RG. Build a power-cut rig: a MOSFET switch on the board’s supply, driven by a second small board that counts a random delay after your node raises a GPIO pin at the start of each save. Run 10,000 cycles. After each cut, restart the node and check that the record has a valid CRC and a sequence number no more than one behind. A good journal never fails. An in-place write fails in roughly the fraction your model predicts.
The record is 256 bytes: 4 + 4 + 244 + 4. We use the STM32 HAL calls for the L4 family. Notice that the write function programs the CRC last, so a half-written record has no valid CRC.
ctypedef struct { uint32_t magic, seq; uint8_t payload[244]; uint32_t crc; } rec_t; /* 256 bytes */ static int rec_valid(const rec_t *r) { return r->magic == REC_MAGIC && r->crc == crc32(r, sizeof(rec_t) - 4); } /* boot: the last valid record wins; slots[] covers both pages (16 slots) */ const rec_t *find_latest(const rec_t *slots, int n) { const rec_t *best = NULL; for (int i = 0; i < n; i++) if (rec_valid(&slots[i]) && (!best || slots[i].seq > best->seq)) best = &slots[i]; return best; } int rec_write(uint32_t addr, rec_t *r) { /* addr: an erased (all 0xFF) slot */ r->magic = REC_MAGIC; r->crc = crc32(r, sizeof(rec_t) - 4); HAL_FLASH_Unlock(); const uint64_t *w = (const uint64_t *)r; for (int i = 0; i < 32; i++) /* 32 x 64 bits, 81.69 us each */ if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, addr + i * 8, w[i]) != HAL_OK) { HAL_FLASH_Lock(); return -1; } HAL_FLASH_Lock(); return 0; }
The failure to remember: this code is safe only because of its order and its CRC. If you add a cache or a write-behind buffer that delays the programming, or if you skip the CRC check when reading, you lose the guarantee without any compiler warning. The test is the rig above, not a code review.
Chapter 7
Replace the running firmware through the radio without ever leaving the node without a program that works
Fifty nodes are in fifty cold stores in three cities. Next month you find a bug in the filter. Nobody will drive to all of them. The fix must arrive through the radio, and it must be safe in a very specific way: whatever happens during the update, the node must still be able to run a program.
The word brick names a device that no longer runs anything and cannot fix itself. Every OTA design is judged by one question: where can the bricks come from? The bootloader lesson covers the variants. We build the one the capstone needs.
Our firmware image is 400 KB. That is 200 pages of 2 KB. The simplest update erases those pages and writes the new image on top of the old one. The datasheet times (Table 50) give the duration. Erasing 200 pages takes 200 × 22.02 ms = 4.40 s. Programming 400 KB is 51,200 words of 64 bits, at 81.69 µs each, which is 4.18 s. Total: 8.58 s.
For 8.58 s the node has either no firmware or half of it. A power cut, a radio drop or a reset in that window leaves a brick. Over fifty nodes and many updates, it will happen. And even if the write succeeds, the naive design cannot tell a good image from a bad one. A transfer error, or a build that hangs at start, bricks the node just as well.
The STM32L476 has 1 MB of flash in two banks of 512 KB (256 pages each). The datasheet says the banks allow read-while-write: the CPU can run code from one bank while the other bank is erased and programmed. It also supports booting from either bank. So the node can keep running the old firmware while the new image is written beside it. In the vocabulary of MCUboot, a widely used open bootloader, the running copy is the primary slot and the new copy goes into the secondary slot.
The safe update is a short story in five steps.
Step 5 is the clever one, and it is why the OTA test needs the watchdog. A new image that hangs cannot confirm itself. But nobody resets a hung chip. Only the watchdog does, after its timeout. That reset gives control back to the bootloader, which sees “test, not confirmed” and restores the old image. Without the watchdog, a hang is permanent.
Choose a design. Drag the power cut along the update. Then switch on a broken image, or an image that hangs, and see what each design does. The watchdog switch matters for the rollback.
Write times from datasheet Table 50 for 200 pages and 51,200 words: 4.40 s and 4.18 s. Hash check 0.12 s, swap 0.20 s, self-test 1.0 s and a 4 s watchdog timeout plus 0.5 s boot are illustrative. The radio download time is left out; it only widens the first stage. Image rules follow the MCUboot design page.
On real hardware: Nucleo-L476RG. Build MCUboot for the board (see the MCUboot docs or Zephyr). Sign three apps: a good one, one with a changed byte after signing, and one whose main is while (1) {}. Update each 20 times with the power rig from Chapter 6 cutting at random points. A passing board always ends up on a working image: new for the good one, old for the other two.
Take the last case in the device: the image is correctly signed, so it passes the check, but its first task never gets to the confirm call. At t = 8.90 s it starts. The self-test would finish at 9.90 s, but the hang stops it. The watchdog (timeout 4 s) fires at 12.90 s. After a 0.5 s boot the bootloader runs at 13.40 s, sees the trial image unconfirmed, and reverts. Cost of the bad release: 4.5 seconds of silence on the radio, and the old firmware back. That is a pass.
c/* In the NEW image, once the self-test passes. */ void app_selftest_and_confirm(void) { if (vs1_read(&raw) == 0 && radio_link_ok() && settings_load() == 0) boot_set_confirmed(); /* MCUboot API: make this image permanent */ /* else do nothing; the next reset reverts to the old image */ } # Build step: sign the image (check `imgtool sign --help` for your version). # imgtool sign --key key.pem --version 1.2.0 --header-size 0x200 --align 8 \ # --slot-size 0x64000 app.bin app_signed.bin # 0x64000 = 400 KB
One caution belongs here. Confirming too early is a trap. If the image confirms itself on the first line of main, a bug that appears two seconds later cannot be reverted. Confirm after the checks that matter: the sensor answers, the radio links, the settings load. The signature protects against a foreign image. It does not protect against your own bug. Only a trial run does.
Chapter 8
Inject the failures a field node will meet, and build the two defences that bring it back without a visit
A forklift pinches the sensor cable in a cold store. The sensor stops in the middle of a byte and holds the data wire low. Your driver waits for the bus to become free. It waits for ever. The node does not crash and does not reset. It simply goes silent, with the LED still lit, and the dashboard says “no data” for two weeks.
Faults like this are not rare. A field product meets them every week. Two tests in our list are about them. Test 5 injects three faults and asks whether the node copes without help. Test 6 freezes a task and asks whether the node heals by itself. The fail-safe lesson covers the safety vocabulary. Here we build the two defences.
The rule is short: every wait has a timeout, and every timeout has a plan. Our read from Chapter 2 already carries a 2 ms timeout and returns −1. Now we must decide what the caller does with that −1. We inject three faults to find out.
The sensor is stuck in the middle of a byte and holds SDA low. Choose how many clock pulses it needs before it lets go. Then switch the bus clear off, or make the sensor never let go.
A model of the procedure in UM10204 section 3.1.16, at about 100 kHz (10 µs per pulse). Real sensors differ in how they stick; some need a reset pin or a power cycle, which is why the fallback exists.
On real hardware: Nucleo-L476RG. Hold the SDA wire to ground with a jumper for 50 ms in the middle of a read, using a second GPIO as an open-drain pull-down on a timer. Look at SCL and SDA on a logic analyzer. A good build shows the nine pulses, a STOP, and valid data in the next read. A bad build shows a flat line.
Some faults you did not think of. A pointer bug, a lost lock or a stack overflow can freeze a task for ever. For these, you use a watchdog timer: a hardware counter that counts down and resets the chip if software does not “kick” it (reload it) in time. The STM32L476 has an independent watchdog (IWDG). The datasheet says it has a 12-bit down-counter and an 8-bit prescaler, runs from its own 32 kHz internal RC oscillator, and works in Stop and Standby too.
The timeout is a small formula. With reload value RL and prescaler divider D, one count lasts D ÷ 32,000 s, and the timeout is (RL + 1) × D ÷ 32,000 s. Table 75 gives the extremes: 0.125 ms to 512 ms with /4, and 8 ms to 32,768 ms with /256. For our 4 s limit, choose /32 and RL = 3,999: 4,000 × 32 ÷ 32,000 = 4.000 s. The datasheet adds that the RC oscillator is not exact; there is a full RC period of uncertainty, and the frequency varies with temperature, so never depend on the third decimal.
Where you kick matters more than the number. Three styles show up in real code.
Pick where the kick comes from, then pick which task freezes at 2.2 s. The sawtooth is the watchdog counter. A reset happens when it reaches zero.
Illustrative schedule: the interrupt kicks every 0.5 s, the sensor task every 0.16 s, the supervisor every 1.0 s. Timeout 4 s (prescaler /32, reload 3,999), boot time 0.5 s. Counter and prescaler behaviour from datasheet section 3.24.5 and Table 75.
On real hardware: Nucleo-L476RG. Add a debug command that runs while (1) {} inside one chosen task. Toggle a GPIO pin each time the chip boots. Measure the time between the freeze and the next boot pulse with a scope. It should be near the timeout plus your boot time, and the log should show an IWDG reset cause.
cIWDG_HandleTypeDef hiwdg = { .Instance = IWDG, .Init = { .Prescaler = IWDG_PRESCALER_32, .Reload = 3999, .Window = IWDG_WINDOW_DISABLE } }; /* 4.000 s */ static volatile uint32_t alive; /* one bit per task */ void checkin(uint32_t bit) { __atomic_or_fetch(&alive, bit, __ATOMIC_RELAXED); } static void supervisor_task(void *arg) { const uint32_t ALL = BIT_SENSOR | BIT_RADIO; for (;;) { vTaskDelay(pdMS_TO_TICKS(1000)); uint32_t a = __atomic_exchange_n(&alive, 0, __ATOMIC_RELAXED); if ((a & ALL) == ALL) HAL_IWDG_Refresh(&hiwdg); /* every task is alive: kick */ /* else: do NOT kick; the chip resets in about 4 s */ } } /* early in boot: say why we restarted, then clear the flags */ if (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST)) log_event(EV_WATCHDOG_RESET); if (__HAL_RCC_GET_FLAG(RCC_FLAG_BORRST)) log_event(EV_BROWNOUT_RESET); __HAL_RCC_CLEAR_RESET_FLAGS();
Three loose ends. First, the IWDG keeps running in Stop 2, so the node must wake and kick before the timeout, however deep it sleeps. The longest timeout is 32.768 s. With a 60 s report period you would still wake every 30 s or so, which costs almost nothing. Second, the stack overflow, our fourth fault, has its own guard: FreeRTOS can fill each task’s stack with a known pattern and check it on every switch (configCHECK_FOR_STACK_OVERFLOW), and the stack lesson goes deeper. Third, a reset hides the cause unless you log it. The reset flags above are how you tell a watchdog reset from a brown-out in the field.
Chapter 9
Turn the six acceptance tests into a ladder of cheaper tests, and learn which rung catches which bug
It is the day before delivery. You run the six acceptance tests by hand: a week of bench time, one power-cut rig, one power profiler, one engineer watching a scope. It passes. Then you fix a typo in the filter and ask the question every team asks: do we have to do the whole week again?
If the answer is yes, you will skip it, and the next bug ships. The answer must be no. This chapter shows how to build a ladder of tests, from seconds on a laptop to hours on a rig, so that each bug is caught on the cheapest rung that can see it. The firmware testing lesson goes deep on each rung.
Valvano and Yerraballi end their book with a design chapter whose advice is plain. Split the system into modules. Give each module a header file (its public functions), a code file (the implementation) and a test main (a small program that exercises only that module). Test each module alone, then join them. We follow it exactly. The sensor driver, the journal and the supervisor each get a test main.
Here is a host test: it compiles on your laptop with a fake bus in place of the real I2C. The fake lets us feed any bytes and any failure we want.
c/* test_vs1.c: runs on the PC. fake_i2c.c replaces HAL_I2C_Mem_Read. */ static void test_decode_negative(void) { uint8_t bytes[6] = { 0x34, 0x12, 0xF0, 0xFF, 0x10, 0x27 }; fake_i2c_set_reply(bytes, 6); vs1_raw_t r; ASSERT_EQ(vs1_read(&r), 0); ASSERT_EQ(r.x, 4660); ASSERT_EQ(r.y, -16); ASSERT_EQ(r.z, 10000); /* the sign bug dies here */ } static void test_nack_is_reported(void) { fake_i2c_fail_next(HAL_ERROR); /* inject the fault, no wire needed */ vs1_raw_t r; ASSERT_EQ(vs1_read(&r), -1); } int main(void) { test_decode_negative(); test_nack_is_reported(); puts("vs1: ok"); return 0; }
Both tests run in milliseconds. You can run them on every save. The first one would have caught the sign bug of Chapter 2. The second catches a driver that hides errors. Neither needs a board.
The rule is to push every bug down the ladder. The first time a bug is caught on rung B or R, you write a rung H or F test that would have caught it, so that it never costs a bench hour again.
Pick a bug. The dots in its row show the rungs that can catch it. The cheapest rung is the leftmost dot. Notice that some bugs fail none of the six acceptance tests.
This grid is a judgement, not a measurement: whether a rung catches a bug depends on how good the fake, the emulator model and the rig are. The times per rung are typical orders of magnitude, not benchmarks.
On real hardware: Nucleo-L476RG. Pick one bug from the grid, put it into the firmware on purpose, and see which rungs catch it. If a rung that the grid says should catch it stays green, your test is too weak. Fix the test, not the grid.
We said a sample needs 1,500 cycles. That was a guess, and the latency and battery tests depend on it. The Cortex-M4 has a cycle counter in its debug block (the DWT unit). Read it before and after the function, and you have the real number.
cstatic inline void cyc_init(void) { CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; /* enable the trace block */ DWT->CYCCNT = 0; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; /* count CPU cycles */ } uint32_t t0 = DWT->CYCCNT; process_batch(fifo_buf, 16, &summary); uint32_t per_sample = (DWT->CYCCNT - t0) / 16; /* put this number into the model */
If the real figure is 3,000 cycles, redo Chapter 3 with it. Latency at 16 MHz becomes 2.235 + 3.0 = 5.2 ms, over the limit, and you will want 24 MHz or a cheaper filter. This is the use of a model: it tells you which number to go and measure, and what to do when it moves.
The acceptance tests themselves should be a script, not a checklist. Latency: toggle a pin on the interrupt and on the handled event, and compare on a logic analyzer. Battery: run the profiler for a minute and compute the average. Power cut: the rig cuts at 1,000 random points of a save loop and the script checks the CRC after each. OTA: three images, many cuts. Faults: the rig shorts SDA, a host command injects a bad sample, a bench supply dips. Watchdog: a debug command freezes each task in turn. The script prints six lines, each with its number and its limit, and its exit code is zero only when all six pass. That is the report the customer reads.
Chapter 10
Keep the numbers, the checklist and the skeleton of the whole node, and see where to go next
A sensor node is a stack of small promises. A clock that you chose on purpose. A driver that reports errors. An interrupt and a DMA copy that let the CPU sleep. Tasks with priorities so the urgent job wins. A sleep budget measured, not guessed. A flash record that no power cut can destroy. An update that can roll back. Timeouts, a bus clear and a supervised watchdog. And a ladder of tests that finds each bug in the cheapest place. Remove one of the big layers and at least one of the six tests fails. That is the whole lesson.
Everything marked “datasheet” comes from the STM32L476xx datasheet (DocID025976 Rev 2) that we opened for this lesson. The rest are choices we made, and you should replace them with your own product’s numbers.
| Quantity | Value | Where it comes from |
|---|---|---|
| Flash layout | 1 MB in 2 banks of 512 KB; 256 pages of 2 KB per bank; read-while-write across banks | Datasheet section 3.4 |
| Run current | 100 µA/MHz headline; 131 µA/MHz (10.5 mA) at 80 MHz | Datasheet features, Table 30 |
| Sleep current at 16 MHz | 0.61 mA | Datasheet Table 31 |
| Stop 2 current | 1.1 µA; 1.4 µA with RTC | Datasheet features, Table 35 |
| Standby with RTC | 0.42 µA | Datasheet features |
| Wake from Stop 2 to Run | 7.3 µs (HSI16); 10.6 µs (MSI 4 MHz) | Datasheet Table 40 |
| Page erase | 22.02 ms typical, 24.47 ms maximum | Datasheet Table 50 |
| Program 64 bits; 256 bytes | 81.69 µs; 2.61 ms | Datasheet Table 50 |
| Erase endurance | at least 10,000 cycles per page | Datasheet Table 51 |
| IWDG timeout range | 0.125 ms to 32,768 ms; (RL + 1) × D ÷ 32,000 s | Datasheet Table 75 |
| I2C read of n bytes | 30 + 9n bit-times; 210 µs for 6 bytes at 400 kHz | UM10204 frame rules |
| Interrupt entry | 12 cycles, Cortex-M4, zero wait states | Arm documentation |
| Battery budget | 91.3 µA = 1,000 mAh × 0.8 ÷ 8,760 h | Our choice |
| Shipped design | 3.74 ms latency, 44.0 µA (2.07 years), 0 of 246 cuts lose data, 8.58 s OTA write, 4.5 s hang recovery | The models in this lesson |
cint main(void) { HAL_Init(); clock_init_16mhz(); /* ch 1: HSI16, wait for ready flags */ report_reset_cause(); /* ch 8: IWDG or BOR? log it, clear the flags */ settings_load(); /* ch 6: scan records, last valid CRC wins */ vs1_init(16); /* ch 2/3: FIFO watermark 16, interrupt pin armed */ iwdg_start(); /* ch 8: /32, reload 3999 = 4.000 s */ xTaskCreate(sensor_task, "sensor", 256, NULL, 3, &sensor_task_h); /* ch 4 */ xTaskCreate(radio_task, "radio", 384, NULL, 2, NULL); xTaskCreate(supervisor_task, "super", 128, NULL, 4, NULL); /* ch 8 */ xTaskCreate(confirm_task, "ok", 128, NULL, 1, NULL); /* ch 7: self-test, then boot_set_confirmed() */ vTaskStartScheduler(); /* idle task sleeps in Stop 2 (ch 5), tickless (ch 4) */ for (;;) {} }
This node is bare Arm Cortex-M firmware with FreeRTOS. The same six tests apply to a node built on Zephyr, where the build system, the drivers and MCUboot are already integrated, and to one written in Rust, where the compiler enforces some of the ownership rules that we enforced by hand. The layers do not change; the amount of work you write yourself does.
This lesson follows the shape of the capstone projects in CMU 18-349 Introduction to Embedded Systems (its course page lists hands-on labs with processors, sensors and actuators and names no instructor) and the design chapter of John Valvano and Ramesh Yerraballi’s Embedded Systems: Shape the World, chapter 10, which stresses a requirements document and modular design with a test main per module. That book is licensed CC BY-NC-ND 4.0, so we ground on its ideas and reproduce none of its text or figures. All the explanations, models and code here are our own.
Sources we opened and read: the STM32L476xx datasheet (every table cited above), the MCUboot design page (slots, test and confirm, revert, trailer, magic number, hash and signature). Sources whose claims we took from search summaries and did not read in full: the Arm interrupt-latency article (12 cycles), the I2C-bus specification UM10204 (the bus clear of section 3.1.16), and the FreeRTOS low-power documentation (tickless idle). The names of HAL functions and register fields in the code follow the STM32 HAL for the L4 family; check them against your HAL version.
Now press Present or Teach and explain the node out loud, from memory: the six tests, the layer each one needs, and one number for each. Then go back to the build at the top, press Blank firmware, and switch the layers on in the order you would build them. Say what each layer buys before you press it.