Debugging embedded code
A systematic way to find bugs in firmware: reproduce, hypothesise and test; serial logging and LEDs as windows into the chip; divide and conquer; and the bugs that catch everyone.
Lesson 6 of 6 · 30 min · Self-paced · Free
When there is no screen
Your robot's gripper closes, then for no obvious reason opens again. A microcontroller has no screen, and the bug might depend on a motor, a sensor or a timing detail that only happens on the real machine. The core of embedded debugging is not a tool but a method: treat every bug as a small experiment.
The method: reproduce, hypothesise, test
- Reproduce. Find steps that make the bug happen reliably. A bug you can trigger on demand is half solved.
- Observe. Gather facts before guessing. What exactly happens, and when? What changed since it last worked?
- Hypothesise. Propose one specific cause: "the force reading drops below the threshold when the motor starts."
- Test one change at a time. Design a check that would prove the hypothesis wrong. Change one thing, observe, record. Changing three things at once tells you nothing about which one mattered.
- Fix and confirm. Repeat the original steps and check that the bug is gone and nothing else broke. Keep notes as you go.
Let the compiler help first
Compile with warnings on (-Wall, and ideally -Wextra) and read every one. Consider this function, which compiles but contains a classic bug:
#define FAULT 4
int check(int state) {
if (state = FAULT) { /* meant ==, compiles anyway */
return 1;
}
return 0;
}The single = assigns 4 to state, and 4 counts as true, so the function always returns 1. With -Wall, common compilers warn about using an assignment as a condition. That warning costs nothing and finds a bug that could take an hour on a bench.
Serial logging
Most microcontrollers can send text to a computer over a serial (UART) connection, which you will study in the embedded communication module. Printing values is the simplest window into a running chip. Good logs have a timestamp, a level and specific values:
#include <stdio.h>
#include <stdint.h>
static uint32_t fake_ms = 0; /* stands in for a real clock */
static uint32_t millis_now(void) { return fake_ms; }
#define LOG(level, fmt, ...) \
printf("[%6lu ms] %s: " fmt "\n", (unsigned long)millis_now(), level, __VA_ARGS__)
int main(void) {
int raw = 731;
LOG("INFO", "boot, firmware v%d.%d", 1, 4);
fake_ms = 1250;
LOG("DEBUG", "adc raw=%d", raw);
fake_ms = 1260;
LOG("WARN", "grip timeout after %d ms", 2000);
return 0;
}This portable version prints to your terminal:
[ 0 ms] INFO: boot, firmware v1.4
[ 1250 ms] DEBUG: adc raw=731
[ 1260 ms] WARN: grip timeout after 2000 msOn a board, the same macro would send its text over the serial port. Logging the firmware version at start-up shows which code is actually running.
Logging has a cost. Serial is slow. At 115,200 baud, roughly 11,520 bytes per second get through, because each byte takes about 10 bits on the wire. A 40-character line takes about 40 / 11,520 ≈ 3.5 ms. Add a log line inside a 1 kHz control loop and you have just broken its timing. Worse, the delay can hide a timing bug, which then reappears when you remove the log. Log at a reduced rate (for example, one line every 100 passes), log only on changes, or store values in a RAM buffer and print them later.
LEDs and pins as debug signals
When serial is unavailable or too slow, a spare GPIO pin is a fast, honest signal.
- Heartbeat: blink an LED once per second from the main loop. If it stops, the loop is stuck.
- Blink codes: flash an LED two times for "sensor missing", three for "timeout", so a fault can be read without a computer.
- Timing pins: set a pin high at the start of a function and low at the end. An oscilloscope or logic analyser then shows exactly how long it takes and how often it runs. A pin change takes only a few clock cycles, so it barely disturbs timing.
Divide and conquer
When you do not know where the bug is, cut the search space in half repeatedly.
- In the code: disable half the features. If the bug remains, it is in the other half. Repeat.
- In history: if it worked last week, check out a version halfway between then and now, test, and repeat. Version control makes this quick; git even automates it with
git bisect. - In the system: replace parts with known-good ones. Feed the code a fixed, made-up sensor value. If the bug disappears, look at the sensor side; if not, look at the logic.
- Make a minimal example: strip the program down to the fewest lines that still show the bug.
A debug probe, the device used for flashing in the firmware lesson, can also pause the chip at a breakpoint and inspect variables, though stopping time can hide timing bugs.
The usual suspects
Many embedded bugs are one of a short list. Check these early:
- Hardware first: is it powered? Do boards share a common ground? Is the wire on the pin the code thinks it is?
- Pin configuration: pin never set as output, or input floating without a pull-up.
- Missing volatile on a variable shared with an interrupt handler.
- Integer overflow or division before multiplication.
- Array overrun: a loop such as
for (i = 0; i <= N; i++)writes one element past the end of an array, silently corrupting whatever variable sits next in RAM. The compiler usually does not warn. - Stack overflow from large local arrays or deep recursion, and blocking delays that starve other tasks.
- Resets caused by power dips: a motor starting can pull the supply low enough to reset the chip. A boot message in the log reveals this quickly.
Many microcontrollers also have a watchdog timer, which resets the chip unless the program "feeds" it regularly. It cannot fix a bug, but it recovers from a hang.
Recap
Debug like a scientist: reproduce, observe, hypothesise, test one change at a time, then confirm the fix. Turn on compiler warnings first. Use timestamped serial logs, but remember they cost time. Use LEDs and pins for heartbeats, blink codes and timing measurements. Divide and conquer through code, history and hardware. Check the usual suspects, starting with power, ground and wiring, before assuming something exotic.
Project
Bug hunt on paper
This made-up firmware fragment is meant to average eight ADC readings and turn on a warning output if the average exceeds 3,000 mV. It contains at least four bugs drawn from this lesson. Find them on paper first, then compile a desktop version (replacing adc_read with values from an array) to confirm.
#define N 8
uint16_t samples[N];
int alarm_flag; /* also set by an interrupt handler */
void update(void) {
uint16_t total = 0;
for (int i = 0; i <= N; i++) {
samples[i] = adc_read(0);
total += samples[i];
}
uint16_t avg_mv = total / N / 1024 * 3300;
if (alarm_flag = 1 || avg_mv > 3000) {
set_warning(1);
}
}For each bug, name the category from "the usual suspects", explain what would go wrong on a real robot, and write the corrected line.
Deliverables
- A list of at least four bugs, each with its category and real-world effect
- Corrected code that compiles with cc -std=c99 -Wall without warnings
- A short note on how you would confirm each fix
Knowledge check
Check your understanding
Go further
- Debugging (Wikipedia) ↗
Debugging techniques and tools, including those used for embedded systems.
- Watchdog timer (Wikipedia) ↗
How watchdog timers detect and recover from software hangs.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.