10 Embedded Firmware Practices That Prevent Painful Bugs

Ten small habits that make a new board easier to debug: checked return codes, timeouts, calculated buffer sizes, sticky error flags, and a status command that shows the reset cause.

Advertisement

Most bring-up bugs are not hard bugs. A status code was not checked, a wait loop had no timeout, or a buffer was sized for one frame when the test tool sends three. The board still boots and mostly works, so the problem shows up late: a reading that is a bit off, or a hang that happens once a day.

The ten habits below are what I want in the code before the first serious bring-up session. The examples are C on a bare-metal main loop with the STM32 HAL, but the points are general and apply to any microcontroller and any vendor library.

Firmware Evidence Loop Good firmware habits turn assumptions into checks, evidence, and controlled fault handling. Assumption named Runtime check bounded Evidence logged Fault path controlled Diagnosis repeatable
Embedded firmware is easier to debug when assumptions, checks, evidence, and fault handling form a visible loop.

1. Put every hardware assumption into a constant

Imagine you are bringing up a measurement board, and every ADC reading is about nine percent lower than the value on your bench multimeter. The board runs and the plot is stable, so you check the sensor, the wiring and the input filter first. After half an hour you find the reason in the firmware: the formula still calculates with the 3.0 V reference from the first schematic revision, while the new revision uses 3.3 V. The number 3000 was typed directly into the formula, so nobody noticed it in the review.

Every value that comes from the schematic or from a datasheet should be a constant that is defined in one place: reference voltage, ADC range, pin polarity, timer period, pull-up value, sensor scale factor. When the hardware changes you have one line to edit, and a reviewer can compare that line with the schematic.

The same rule covers the values that are easy to forget: which edge a ready pin uses, how long a regulator needs before the ADC result is valid, how long a chip needs after reset. If the number is in a datasheet, make it a constant and write the datasheet section in the comment.

2. Check every driver return value

Say you have a sensor that works after the second power cycle but never after the first. On the first power-up the SPI write to its configuration register fails, because the sensor is still starting. Your code does not look at the return value, so the sensor stays on its reset defaults, and you see the problem much later as a strange measurement, far away from the line that failed.

Every driver call that can fail should return a status that the caller checks, and it should also leave a record. I keep both: the return value for the control flow, and one bit in a global health word that stays set, so that the failure can still be read out later. The function health_report() sets that bit. Its body comes in practice 7, because doing it correctly needs a critical section.

If a retry succeeds later, the bit still shows that the bus failed once in this run. That is often the first hint that the power-up timing is too tight or that a signal is marginal.

3. Keep interrupt handlers short

You are writing the UART receive code, and it is tempting to call the frame parser directly from the receive interrupt, because the last byte has just arrived there. On the bench this works. Later, when the system is busy, you notice that an ADC sample is sometimes taken late, because the UART interrupt was still parsing while the ADC interrupt had to wait.

An interrupt handler should take the data out of the hardware, clear the interrupt condition and return. Parsing, logging, flash writes and decisions belong in the main loop or in a task. The usual tool is a ring buffer with one writer (the interrupt) and one reader (the main loop):

Two details are worth knowing. The head and tail indexes are 16-bit. On a 32-bit Cortex-M the CPU reads or writes them in one access, so this ring needs no lock. On an 8-bit MCU that is not true, and the main loop must disable the interrupt while it reads the head. The second detail is the throughput. One interrupt per byte is fine at 115200 baud. At higher rates the next step is DMA in circular mode together with the idle-line interrupt. The rule stays the same: the interrupt moves bytes and the main loop parses them.

4. Put a timeout on every blocking wait

Imagine your board hangs at startup, and the debugger shows it in a while loop that waits for a ready pin. You do not know if the sensor is missing, if the pin is wrong or if the peripheral clock is off, and the loop cannot tell you, because it was written for hardware that always responds.

Every blocking wait needs a limit, and the timeout needs a separate error code, so that you can tell it apart from other failures.

The 32-bit millisecond tick wraps after about 49.7 days. The form now - start >= timeout gives the right answer across the wrap. The form now > start + timeout does not, and that bug only appears on a device that has been running for seven weeks.

There is one more trap. HAL_GetTick() only counts while the SysTick interrupt runs. Inside an interrupt handler with the same or a higher priority, or with interrupts disabled, the tick stands still and the loop above waits forever again. In those places, use a hardware timer counter or a fixed number of loop passes. For the timeout value, take the maximum from the datasheet and add margin. It can be loose during first bring-up and tighter after the real hardware has been measured.

5. Size buffers for the worst case

You test the serial link with a terminal program and it works: one command, one answer. Then the production test tool sends three frames back to back while your firmware is busy with a flash write, and bytes are lost. When you look for the reason, you find that the ring size is a round number that somebody liked.

A receive buffer has to hold everything that can arrive while nobody reads it. That can be calculated. At 115200 baud with 8N1 framing, one byte needs 10 bit times, so 11520 bytes arrive per second. If the main loop can be away for 20 ms, about 230 bytes pile up in that time.

The 20 ms must be measured. Toggle a GPIO at the top of the main loop and look at the longest period on an oscilloscope while the slow things are running: flash writes, display updates, long calculations. The protocol sets a second limit. If the host may send three 96-byte frames without waiting for an answer, 288 bytes can be on the way even when the firmware is normally fast. After that, the overflow counter from practice 3 shows whether the number was right.

6. Keep raw data separate from converted values

Suppose a temperature value on your display looks wrong. The first thing you want to know is whether the raw counts are wrong or the conversion is wrong. If your driver only returns degrees, you cannot answer that without changing the code.

Keep the raw measurement and the engineering value as two separate steps. The raw count is what the hardware delivered. The converted value already contains the calibration and the formula, and each of them can contain a bug.

The exact gain is 3300000 / 4095 = 805.86 µV per count. Rounding it to 806 gives an error of about 0.6 mV at full scale, which is less than one count. This check is worth doing once for every integer scale factor.

When a value looks wrong, print the raw count next to the converted value. If the raw counts are stable and the result is wrong, look at the calibration and the formula. If the raw counts jump, the problem is earlier: reference, input filter, sampling time or the sensor.

7. Make error flags sticky until they are read

Imagine a sensor timeout that lasts for one cycle, while your host GUI polls the status once per second. The timeout is gone long before the GUI asks, and a CRC error has the same problem when the next good packet overwrites it. If the firmware only reports its current state, you never see the short failures.

A sticky flag stays set until something reads it and clears it. This is the health word from practice 2. The read-modify-write on it needs a critical section, so here are the two small helpers for a Cortex-M first, and then the flag functions.

volatile only tells the compiler to read the variable from memory every time. It does not protect the sequence read, OR, write. Suppose the main loop has read the health word and is interrupted before it writes it back. The interrupt sets its own bit, and then the main loop writes its old copy over it. The bit from the interrupt is gone. The same happens when the snapshot and the clear are two separate steps.

With sticky flags, a host tool can poll once per second and still see a failure that lasted 2 ms.

8. Put a version in the protocol

You update the firmware on your bench board, but the production test program was built last month and still sends the old frame layout. Firmware and host tools are almost never updated at the same moment. Without a version field, your parser accepts the old frame and gives you values that look valid and are wrong.

Put the version in the first byte of the frame and never move it, so that every future version can still find it. Check it before anything else.

The header is decoded byte by byte and not with a cast or a memcpy() into the struct. That keeps the code independent of the byte order and the struct padding of the compiler, and the PC tool can use the same lines. When the version does not match, answer with an error frame that contains the version the firmware supports. The tool can then show “firmware has protocol 2, tool has protocol 3” and the user does not have to debug a timeout. If you ever need more than one frame format, let the tool ask the firmware which formats it supports. Guessing the format from the length or the look of a packet works only until two formats happen to have the same size.

9. Test with hardware missing

When you get the first prototype on your desk, something is always missing: a sensor is not fitted, a cable is wrong, or an option board is still with a colleague. If your firmware only starts when every device answers, you cannot even begin the bring-up.

For every external part, decide what the firmware does without it: switch the feature off, set a flag, go to a safe mode, or run with reduced function. It must not wait forever.

The ID check matters more on SPI than many people expect. On I2C, a missing chip does not acknowledge its address and the driver returns an error. On SPI there is no acknowledge. The transfer succeeds, the MISO line floats or sits on a pull resistor, and the firmware reads 0xFF or 0x00 as if it were data. Only the comparison with the expected ID shows that nobody is there.

Do this test on purpose, once for every optional part: unplug it, power up, and look at what the firmware reports. If one missing module can stop the whole board from booting, fix that before the board goes to other people.

10. Keep a debug path open

On a prototype you need SWD, reset, one UART and a few test points to see what the board is doing. The firmware has its part in this. A small status command that prints the version, the reset cause, the health flags and a few raw readings is cheap to write early, and it often saves more time than a big logging system that is added late.

The reset cause is the field that is forgotten most often. Without it, a watchdog reset looks like a normal power-up and the hang behind it stays hidden.

Plan this path before the layout is finished. If the board is small, test pads and a compact status word are enough. What should not happen is that the only way to look inside the board is removed to save a connector.

Checklist before the board goes to testing

Before I call a board ready for serious testing, I go through these questions:

  • Is every value from the schematic or a datasheet a constant in one place?
  • Is a failed driver call still visible after the function has returned?
  • Does every wait loop have a timeout, and does the timeout work where the tick does not run?
  • Is the receive buffer size calculated, and is there an overflow counter?
  • Does the board boot with each optional part unplugged?
  • Can a host tool or a technician read the version, the reset cause and the health flags?

None of these habits is difficult, and each one costs only a few lines of code. You get that time back on the first bad day at the bench, when the firmware can already tell you what went wrong.

Comments and corrections

Would you like to leave a comment, report a technical error, or flag an outdated detail? Use the form below.

Required fields are marked *. Comments are moderated. Email addresses are not published. Privacy Policy