Debugging code on a [microprocessor](https://www.ampheo.com/c/microprocessors) requires a mix of hardware and software tools. Here's a comprehensive guide to effective debugging techniques: ![1746988879602](https://hackmd.io/_uploads/r1ixvzIwex.jpg) **1. Basic Debugging Methods** **LED Indicators** * Blink LEDs to track program flow * Use different blink patterns for error codes ``` c #define ERROR_MEMORY 0b1010 #define ERROR_SENSOR 0b1100 ``` **Serial Print Debugging** Send debug messages over UART/USB ``` c printf("Sensor value: %d\n", sensor_read()); ``` **2. Hardware Debugging Tools** **Debug Probes** * ST-Link (for [STM32](https://www.ampheo.com/search/STM32)) * J-Link (ARM Cortex) * CMSIS-DAP (ARM) **[Oscilloscope](https://www.onzuu.com/category/oscilloscopes) & Logic Analyzer** * Verify signal timing * Capture protocol traces (I2C, SPI) **3. Software Debugging Tools** **GDB with OpenOCD** ``` bash openocd -f interface/stlink.cfg -f target/stm32f4x.cfg arm-none-eabi-gdb -ex "target remote localhost:3333" ``` **RTOS-Aware Debugging** * FreeRTOS thread visualization * ThreadX task monitoring **4. Advanced Techniques** **Hardware Breakpoints** Set breakpoints without code modification ``` gdb break main.c:42 watch variable_name ``` **Trace Debugging** * ARM ETM instruction trace * Segger SystemView for RTOS **5. Common Debugging Scenarios** **Memory Corruption** * Use MPU (Memory Protection Unit) * Enable stack canaries ``` c #define STACK_CANARY 0xDEADBEEF ``` **Race Conditions** * Logic analyzer for timing analysis * RTOS mutex visualization **6. Debugging Workflow** 1. Reproduce the issue 2. Isolate with binary search 3. Check registers (via GDB info registers) 4. Verify peripheral configurations 5. Review disassembly (disassemble in GDB) **7. Post-Mortem Debugging** * Crash dumps analysis * HardFault handlers ``` c void HardFault_Handler(void) { __asm("TST LR, #4"); __asm("ITE EQ"); __asm("MRSEQ R0, MSP"); __asm("MRSNE R0, PSP"); __asm("B HardFault_Debug"); } ``` **8. Debugging Without Debugger** **Semihosting** ``` c fprintf(stderr, "Error code: %d\n", err); ``` **SWO Trace (ARM Cortex)** Single-wire output for printf **9. Debugging Tips** * Start with known-good code * Verify clock configurations * Check errata sheets * Use version control (git bisect) **10. Common Debugging Tools** ![企业微信截图_20250729172753](https://hackmd.io/_uploads/BkPXNzUvxe.png) For embedded systems, always: 1. Verify hardware connections 2. Check [power supply](https://www.onzuu.com/category/external-internal-power-supply) stability 3. Confirm clock settings 4. Validate linker script addresses