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.
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#define ADC_REF_MV 3300u // VREF+ on board rev B (rev A had 3000) #define ADC_MAX_COUNTS 4095u // 12-bit conversion #define RELAY_ENABLE_GPIO_Port GPIOB #define RELAY_ENABLE_Pin GPIO_PIN_7 #define RELAY_ENABLE_ACTIVE_LOW 1 // low level on the pin switches the relay on static uint32_t adc_counts_to_mv(uint16_t counts) { // Good: reference and range are constants, so a schematic change is one edit. return ((uint32_t)counts * ADC_REF_MV) / ADC_MAX_COUNTS; } static void relay_set(bool enabled) { // Good: callers say "relay on" or "relay off". The polarity is handled here only. bool pin_high = RELAY_ENABLE_ACTIVE_LOW ? !enabled : enabled; HAL_GPIO_WritePin(RELAY_ENABLE_GPIO_Port, RELAY_ENABLE_Pin, pin_high ? GPIO_PIN_SET : GPIO_PIN_RESET); } // Bad: the reference voltage is hidden inside the formula. // uint32_t mv = (counts * 3000u) / 4095u; |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
typedef enum { FW_OK = 0, FW_SPI_TX_FAILED, FW_SENSOR_TIMEOUT, } FirmwareStatus; #define HEALTH_SPI_TX_FAILED (1u << 0) #define HEALTH_SENSOR_TIMEOUT (1u << 1) #define SENSOR_SPI_TIMEOUT_MS 10u void health_report(uint32_t flag); // sets one bit in the health word, see practice 7 static FirmwareStatus sensor_write_reg(uint8_t reg, uint8_t value) { uint8_t tx[2] = { reg, value }; if (HAL_SPI_Transmit(&hspi1, tx, sizeof(tx), SENSOR_SPI_TIMEOUT_MS) != HAL_OK) { // Good: the caller gets the error now, and the bit stays set for later. health_report(HEALTH_SPI_TX_FAILED); return FW_SPI_TX_FAILED; } return FW_OK; } // Bad: (void)HAL_SPI_Transmit(...); // a failed transfer leaves no trace. |
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):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#define UART_RX_RING_SIZE 512u // where this number comes from: practice 5 #define HEALTH_UART_RX_OVERFLOW (1u << 2) #define HEALTH_UART_REARM_FAILED (1u << 3) static uint8_t rx_ring[UART_RX_RING_SIZE]; static volatile uint16_t rx_head; // written only by the interrupt static volatile uint16_t rx_tail; // written only by the main loop static volatile uint32_t uart_rx_overflow_count; static uint8_t rx_byte; static void ring_push_from_isr(uint8_t b) { uint16_t next = (uint16_t)((rx_head + 1u) % UART_RX_RING_SIZE); if (next == rx_tail) { // Good: a full ring drops the byte and records it. Nothing is parsed here. health_report(HEALTH_UART_RX_OVERFLOW); uart_rx_overflow_count++; return; } rx_ring[rx_head] = b; rx_head = next; } void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if (huart == &huart2) { ring_push_from_isr(rx_byte); // Good: the re-arm can fail too. If nobody checks it, reception stops silently. if (HAL_UART_Receive_IT(&huart2, &rx_byte, 1u) != HAL_OK) { health_report(HEALTH_UART_REARM_FAILED); } } } // Main loop side: take one byte out of the ring if there is one. static bool ring_pop(uint8_t *out) { if (rx_tail == rx_head) { return false; } *out = rx_ring[rx_tail]; rx_tail = (uint16_t)((rx_tail + 1u) % UART_RX_RING_SIZE); return true; } // Bad: calling protocol_parse_full_frame() from the callback above. |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
typedef enum { ADC_SAMPLE_OK = 0, ADC_SAMPLE_TIMEOUT, } AdcSampleStatus; static bool adc_ready_pin_is_high(void) { return HAL_GPIO_ReadPin(ADC_READY_GPIO_Port, ADC_READY_Pin) == GPIO_PIN_SET; } static AdcSampleStatus adc_wait_ready(uint32_t timeout_ms) { uint32_t start = HAL_GetTick(); while (!adc_ready_pin_is_high()) { // Good: unsigned subtraction stays correct when the tick counter wraps. if ((HAL_GetTick() - start) >= timeout_ms) { health_report(HEALTH_SENSOR_TIMEOUT); return ADC_SAMPLE_TIMEOUT; } } return ADC_SAMPLE_OK; } // Bad: while (!adc_ready_pin_is_high()) {} // hangs forever if the pin never rises. // Risky: if (HAL_GetTick() > start + timeout_ms) // wrong when the sum wraps. |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#define UART_BAUD 115200u #define UART_BITS_PER_BYTE 10u // start bit + 8 data bits + stop bit #define MAIN_LOOP_WORST_GAP_MS 20u // longest time the main loop does not read // Bytes that arrive while the main loop is away: 11520 bytes/s * 20 ms = 230. #define RX_BYTES_DURING_GAP \ (((UART_BAUD / UART_BITS_PER_BYTE) * MAIN_LOOP_WORST_GAP_MS) / 1000u) // Good: the build fails when the ring no longer fits the calculation. // Tradeoff: factor 2, because the 20 ms is a measurement and can miss a rare case. _Static_assert(UART_RX_RING_SIZE >= (2u * RX_BYTES_DURING_GAP), "UART RX ring is too small for the worst main-loop gap"); // Bad: #define UART_RX_RING_SIZE 256u // why 256? Nobody knows a year later. |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
typedef struct { int16_t offset_counts; uint32_t gain_uV_per_count; // 806 for a 3.3 V reference and 12 bits } AdcCalibration; typedef struct { uint16_t raw_counts; uint32_t timestamp_ms; } RawAdcSample; static RawAdcSample adc_capture_raw(void) { RawAdcSample sample = { // Good: the raw count is kept, with the time it was taken. .raw_counts = adc_read_raw_counts(), .timestamp_ms = HAL_GetTick(), }; return sample; } static int32_t adc_raw_to_microvolts(RawAdcSample sample, const AdcCalibration *cal) { int32_t corrected = (int32_t)sample.raw_counts - cal->offset_counts; // Good: the conversion is a separate function and can be tested on a PC. // Note: 4095 counts * 806 uV is about 3.3 million, far below the int32_t limit. return corrected * (int32_t)cal->gain_uV_per_count; } // Bad: the ADC driver returns only millivolts and throws the count away. |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
static volatile uint32_t system_health; static inline uint32_t enter_critical(void) { uint32_t primask = __get_PRIMASK(); // remember if interrupts were enabled __disable_irq(); return primask; } static inline void exit_critical(uint32_t primask) { // Good: restore the old state. Do not enable blindly, the caller // may itself be inside a critical section or an interrupt handler. __set_PRIMASK(primask); } void health_report(uint32_t flag) { // Good: volatile does not make |= atomic. Without the critical section, // an interrupt between the read and the write loses a flag. uint32_t state = enter_critical(); system_health |= flag; exit_critical(state); } uint32_t health_read_and_clear(void) { // Good: copy and clear in one critical section, so a flag that arrives // between the two steps is not lost. uint32_t state = enter_critical(); uint32_t snapshot = system_health; system_health = 0u; exit_critical(state); return snapshot; } // Bad: clearing the error flag because the next sample was good. |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#define PROTOCOL_VERSION 2u #define PROTOCOL_MAX_PAYLOAD 128u #define FRAME_HEADER_BYTES 4u #define HEALTH_PROTOCOL_VERSION_MISMATCH (1u << 4) #define HEALTH_BAD_PACKET_LENGTH (1u << 5) typedef struct { uint8_t version; uint8_t type; uint16_t payload_len; } FrameHeader; static bool protocol_decode_header(const uint8_t raw[FRAME_HEADER_BYTES], FrameHeader *header) { header->version = raw[0]; header->type = raw[1]; // Good: the byte order is written out (low byte first on the wire). header->payload_len = (uint16_t)(raw[2] | ((uint16_t)raw[3] << 8)); if (header->version != PROTOCOL_VERSION) { // Good: an old tool or an old firmware gets a clear error. health_report(HEALTH_PROTOCOL_VERSION_MISMATCH); return false; } if (header->payload_len > PROTOCOL_MAX_PAYLOAD) { // Good: the length is checked before any code copies the payload. health_report(HEALTH_BAD_PACKET_LENGTH); return false; } return true; } // Bad: memcpy() the received bytes into the struct and trust payload_len. |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
typedef enum { SENSOR_PRESENT = 0, SENSOR_MISSING, SENSOR_UNSUPPORTED_ID, } SensorProbeResult; #define HEALTH_SENSOR_NOT_FOUND (1u << 6) #define HEALTH_SENSOR_BAD_ID (1u << 7) static SensorProbeResult sensor_probe(void) { uint8_t id = 0u; if (sensor_read_id(&id) != FW_OK) { // Good: no answer is a normal result with a defined reaction. health_report(HEALTH_SENSOR_NOT_FOUND); return SENSOR_MISSING; } if (id != EXPECTED_SENSOR_ID) { // Good: a wrong ID is reported separately from a missing chip. health_report(HEALTH_SENSOR_BAD_ID); return SENSOR_UNSUPPORTED_ID; } return SENSOR_PRESENT; } // Bad: assume the sensor is fitted and block the startup until it answers. |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
typedef enum { RESET_UNKNOWN = 0, RESET_POWER_ON, RESET_WATCHDOG, RESET_SOFTWARE, RESET_PIN, } ResetCause; // Call once at startup and store the result. static ResetCause read_reset_cause(void) { ResetCause cause = RESET_UNKNOWN; // Note: flag names from the STM32F4 HAL; other families differ a little. // The pin flag is checked last, because the other resets set it too. if (__HAL_RCC_GET_FLAG(RCC_FLAG_IWDGRST)) { cause = RESET_WATCHDOG; } else if (__HAL_RCC_GET_FLAG(RCC_FLAG_SFTRST)) { cause = RESET_SOFTWARE; } else if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST)) { cause = RESET_POWER_ON; } else if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST)) { cause = RESET_PIN; } // Good: clear the flags, or the next boot reports this reset again. __HAL_RCC_CLEAR_RESET_FLAGS(); return cause; } static void debug_print_status(ResetCause reset_cause) { debug_write("fw=%lu reset=%u health=0x%08lX\r\n", (unsigned long)FW_VERSION_U32, (unsigned)reset_cause, (unsigned long)system_health); // Good: counters and raw numbers, so the first look already narrows it down. debug_write("uart_overflows=%lu last_adc=%u\r\n", (unsigned long)uart_rx_overflow_count, (unsigned)adc_get_last_raw_counts()); } // Bad: debug_write("failed\r\n"); // says nothing about what failed or why. |
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.