Firmware Programming

Debugging Microcontrollers With JTAG, SWD and GDB

On-chip debugging explained: JTAG vs SWD, debug probes, OpenOCD and GDB sessions, breakpoints, HardFault analysis, SWO/RTT output and connection fixes.

On this page
  1. How on-chip debugging works
  2. JTAG vs. SWD
  3. Debug probes
  4. Wiring the debug connection
  5. Setting up a GDB session
  6. GDB commands you’ll use constantly
  7. Breakpoints and watchpoints on microcontrollers
  8. Using the debugger from an IDE
  9. Debugging a Cortex-M HardFault
  10. Getting output without a UART
  11. Troubleshooting: when the debugger won’t connect
  12. Debug ports and production devices

Print statements only get you so far in firmware. A hardware debugger lets you stop the processor, step through code line by line, inspect variables, registers and peripheral state, and catch the instruction that caused a crash, all while the code runs on the real chip. On most modern microcontrollers this works through JTAG or SWD, with GDB (or an IDE built on it) as the user interface.

This guide explains how the pieces fit, then walks through a working setup, everyday GDB commands, fault analysis and the problems that most often stop a debugger from connecting.

How on-chip debugging works

Three components sit between you and the chip:

  1. Debug logic on the chip. On Arm Cortex-M parts this is the CoreSight debug architecture. It can halt the core, read and write memory and registers, and set hardware breakpoints and watchpoints.
  2. A debug probe. This small USB device converts commands from your PC into JTAG or SWD signals.
  3. Software on the PC:
    • A debug server such as OpenOCD, pyOCD or SEGGER’s J-Link GDB Server. It talks to the probe and exposes a GDB remote connection, usually a TCP port.
    • GDB (arm-none-eabi-gdb or gdb-multiarch for Arm). It loads your ELF file’s symbols and lets you control the target.

IDEs such as STM32CubeIDE, MCUXpresso, or VS Code with the Cortex-Debug extension run these same pieces behind the scenes.

JTAG vs. SWD

JTAG

JTAG (IEEE 1149.1) started as a standard for boundary scan, a way to test the solder joints and connections on a manufactured board. It was later widely adopted for processor debugging. It uses four or five signals:

  • TCK: clock
  • TMS: mode select (drives the test-port state machine)
  • TDI: data in
  • TDO: data out
  • TRST: optional test reset

Several JTAG devices can be daisy-chained on one port. That’s useful on boards with an FPGA, a processor and other chips.

SWD

Serial Wire Debug (SWD) is Arm’s two-wire alternative:

  • SWDIO: bidirectional data
  • SWCLK: clock

An optional third pin, SWO (Serial Wire Output), streams trace and printf-style data from the chip. SWD reaches the same Arm debug features as JTAG with fewer pins, which matters on small packages. Many Cortex-M parts support both. Some, including most Cortex-M0 and M0+ devices, support only SWD.

Which should you use?

JTAG SWD
Signals 4–5 (TCK, TMS, TDI, TDO, TRST) 2 (SWDIO, SWCLK) + optional SWO
Architectures Many (Arm, RISC-V, FPGAs, DSPs, others) Arm Cortex parts
Daisy-chaining Yes No (one target per port, in typical use)
Boundary scan Yes No
Typical use Multi-chip boards, non-Arm targets, production test Most Arm microcontroller projects

For an Arm Cortex-M project, SWD is the usual choice. JTAG matters for non-Arm targets (many RISC-V chips, the original ESP32), FPGAs, and boards where boundary-scan testing is part of production.

Other vendors have their own debug interfaces. Examples include debugWIRE and UPDI on AVR chips, and Microchip’s ICSP-based debugging on PIC. The GDB concepts below still apply, but the probes and tools differ.

Debug probes

Probe Notes
ST-LINK (V2, V3) Built into most STM32 Nucleo and Discovery boards; supported by OpenOCD, pyOCD and ST’s tools
SEGGER J-Link Widely used commercial probe with broad device support, fast flash programming and RTT; educational/hobby editions exist
CMSIS-DAP probes Open Arm standard; includes DAPLink-based boards, the Raspberry Pi Debug Probe and many low-cost probes
Black Magic Probe Runs a GDB server on the probe itself, so no separate debug server is needed
ESP-Prog / built-in USB-JTAG For ESP32; newer parts such as ESP32-C3 and ESP32-S3 include USB-JTAG on-chip
Microchip PICkit, MPLAB Snap/ICD, Atmel-ICE For PIC, AVR and Microchip SAM devices, mainly with MPLAB X

If your board has an onboard probe, start with that. Buy a separate probe when you move to your own boards.

Wiring the debug connection

For SWD you need at least:

  • SWDIO, SWCLK
  • GND (always)
  • VTref: target voltage reference, so the probe matches your logic level
  • NRST: reset. Optional, but strongly recommended.
  • SWO: optional, for trace output

Common connectors are the 10-pin 0.05” Cortex Debug connector and the older 20-pin 0.1” Arm JTAG connector. Tag-Connect cables are an option when you want no connector on the board. Keep wires short. Long jumper wires are a frequent cause of unreliable connections at higher SWD clock speeds.

Setting up a GDB session

The example below uses OpenOCD with an ST-LINK and an STM32F4. Other probes and chips follow the same pattern with different configuration files.

Build with debug information

Compile with -g so GDB can map machine code back to your source lines and variables. Debug info is stored in the ELF file and isn’t flashed to the chip. For easier stepping, consider -Og (optimize, but keep code debuggable) during development. At -O2 or -Os, variables may show as <optimized out> and stepping can appear to jump around.

Start the debug server

openocd -f interface/stlink.cfg -f target/stm32f4x.cfg

OpenOCD connects to the probe, identifies the chip and, by default, listens for GDB on port 3333. It also opens a telnet console on port 4444. Other probes and servers work similarly.

A CMSIS-DAP probe with a Raspberry Pi Pico (RP2040):

openocd -f interface/cmsis-dap.cfg -f target/rp2040.cfg

SEGGER J-Link, whose GDB server listens on port 2331 by default:

JLinkGDBServer -device STM32F407VG -if SWD -speed 4000

pyOCD, which listens on port 3333 by default:

pyocd gdbserver --target stm32f407vg

Connect GDB, load and run

$ arm-none-eabi-gdb build/firmware.elf
(gdb) target extended-remote localhost:3333
(gdb) monitor reset halt
(gdb) load
(gdb) break main
(gdb) continue
  • target extended-remote connects to the debug server.
  • monitor ... passes a command straight to OpenOCD (here, reset the chip and halt it).
  • load programs the ELF file into flash.
  • break main and continue run to the start of main().

With a Black Magic Probe, you connect directly to its serial port instead:

(gdb) target extended-remote /dev/ttyACM0
(gdb) monitor swdp_scan
(gdb) attach 1

To avoid retyping, put the setup commands in a file and run arm-none-eabi-gdb -x debug.gdb build/firmware.elf.

GDB commands you’ll use constantly

Command What it does
break file.c:42 / b func Set a breakpoint
continue / c Resume execution
next / n Step over a line (don’t enter calls)
step / s Step into a function
finish Run until the current function returns
stepi / si Step one machine instruction
print var / p var Show a variable; p/x var for hex
p *ptr@8 Show 8 elements starting at ptr
x/8xw 0x20000000 Examine 8 words of memory in hex
info registers Show CPU registers
backtrace / bt Show the call stack
watch var Stop when var is written
display var Print var every time execution stops
info breakpoints / delete N List or remove breakpoints
monitor reset halt Reset and halt the target (OpenOCD)
disassemble Show the machine code around the current PC

Peripheral registers can be read like memory if you know their address. IDEs and the VS Code Cortex-Debug extension can also show them by name using the chip’s SVD file.

Breakpoints and watchpoints on microcontrollers

On a PC, GDB sets a breakpoint by temporarily replacing an instruction in RAM. Firmware usually runs from flash, which can’t be rewritten that way, so breakpoints in flash use hardware comparators in the debug unit. There are only a few of them. A Cortex-M3 or M4 typically provides around six hardware breakpoints, and Cortex-M0/M0+ parts often have up to four. The exact number depends on the chip.

If you set more breakpoints than the hardware supports, GDB or the debug server will report an error when you resume. Delete ones you no longer need.

Watchpoints (watch, rwatch, awatch) use the separate data watchpoint unit. They stop the processor when a memory location is written or read. They’re very effective for finding out what is corrupting a variable. Cortex-M parts typically provide only a small number (often two to four), and each can cover only a limited, aligned range.

Using the debugger from an IDE

Most people use the same machinery through a GUI:

  • Vendor IDEs (STM32CubeIDE, MCUXpresso, MPLAB X, Code Composer Studio) come preconfigured for their own chips and onboard probes.
  • VS Code + Cortex-Debug works with OpenOCD, pyOCD, J-Link and others. It adds register and peripheral views (from SVD files), memory views and RTOS thread awareness.
  • Keil, IAR, SEGGER Embedded Studio have their own integrated debuggers.

It still helps to know the GDB layer underneath. When the GUI says “failed to connect”, the debug server’s log usually explains why. For more on choosing these tools, see embedded development tools: IDEs, toolchains and simulators.

Debugging a Cortex-M HardFault

A HardFault means the processor hit an error it couldn’t handle, such as a bad memory access, an undefined instruction or a divide by zero with trapping enabled. Your program typically ends up in an infinite loop in HardFault_Handler. To find the cause:

1. Read the fault status registers. These addresses are standard on Armv7-M parts such as Cortex-M3, M4 and M7:

Register Address What it tells you
CFSR 0xE000ED28 Configurable fault status: MemManage, BusFault and UsageFault bits
HFSR 0xE000ED2C HardFault status, including whether a lower-priority fault escalated
MMFAR 0xE000ED34 Faulting address, valid if MMARVALID is set in CFSR
BFAR 0xE000ED38 Faulting address, valid if BFARVALID is set in CFSR
(gdb) x/xw 0xE000ED28
(gdb) x/xw 0xE000ED2C

The bits in CFSR tell you the kind of fault: a precise bus error, an unaligned access, an undefined instruction, an attempt to switch to Arm state, and so on. Your core’s reference manual lists each bit. Cortex-M0/M0+ cores don’t have these fault status registers, so on those parts you rely mostly on the stacked PC.

2. Find the instruction that faulted. On exception entry, the core pushes eight registers onto the stack: R0–R3, R12, LR, PC and xPSR. The stacked PC is the seventh word (offset 0x18). In the fault handler, bit 2 of the LR value (EXC_RETURN) tells you which stack was in use: 0 for the main stack (MSP), 1 for the process stack (PSP, used by most RTOS tasks).

(gdb) p/x $lr
(gdb) x/8xw $sp
(gdb) info symbol 0x08001a3c
(gdb) list *0x08001a3c

Here x/8xw $sp dumps the exception frame when the main stack was in use. Replace 0x08001a3c with the stacked PC value you found, and list * shows the matching source line. Make sure $sp is the stack pointer the core used for the exception frame. If the handler has already pushed its own registers, adjust for that, or read the frame from a small assembly wrapper that passes the correct stack pointer to a C function.

Common culprits include stack overflow, dereferencing a NULL or stale pointer, calling through a corrupted function pointer, accessing a peripheral whose clock isn’t enabled, and unaligned access to packed structs.

Getting output without a UART

  • SWO / ITM: On Cortex-M3/M4/M7 parts with an SWO pin, the ITM can stream printf-style output through the debug connection. It needs the SWO pin wired to the probe and the trace clock configured correctly.
  • SEGGER RTT: Real-Time Transfer exchanges data through a buffer in RAM that the probe reads in the background. It’s very fast and needs no extra pins. J-Link supports it natively, and OpenOCD and probe-rs also offer RTT support.
  • Semihosting: lets the target use the host PC’s console and files through the debugger. It’s convenient for tests, but every call halts the core briefly, so it’s slow. Firmware that uses semihosting will typically fault if no debugger is attached, so keep it out of release builds.

For timing problems, a GPIO toggled at key points and watched on a logic analyzer or oscilloscope is often the least intrusive tool of all.

Troubleshooting: when the debugger won’t connect

Work through these in order:

  1. Power and ground. Is the target powered? Is GND connected between probe and target? Is VTref connected?
  2. Wiring. Check SWDIO and SWCLK aren’t swapped, keep wires short, and lower the adapter speed (for example adapter speed 1000 in OpenOCD) to test.
  3. Reset. Connect NRST and try connecting under reset, so the probe holds the chip in reset while it attaches. In OpenOCD this is set with reset_config options such as connect_assert_srst. Many vendor tools have a “connect under reset” checkbox.
  4. Firmware disabled the debug pins. If your code reconfigures the SWD pins as GPIO, or puts the chip into a low-power mode early in startup, the debugger can’t attach once the code runs. Connecting under reset usually recovers the chip. Some chips also need a boot-mode pin set so the bad firmware doesn’t run.
  5. Low-power modes. Sleep and stop modes can switch off the debug logic. On STM32, bits in the DBGMCU control register keep debug active in low-power modes during development.
  6. Read-out protection. If flash protection is enabled, the debugger may connect but be unable to read flash, or may be blocked entirely. On STM32, lowering protection from level 1 to level 0 mass-erases the flash. Level 2 permanently disables debugging and can’t be undone, so be very careful with it.
  7. Wrong target or config. Check that the OpenOCD target file, J-Link device name or pyOCD target matches your exact chip.
  8. Driver or permission issues. On Linux, probes often need udev rules to be accessible without root. On Windows, make sure the right USB driver is installed.

Debug ports and production devices

An open debug port lets anyone with a probe read your firmware and change device behavior. For shipping products, consider:

  • Read-out protection or debug lock features, chosen carefully because some levels are irreversible
  • Secure debug schemes on chips that support them, where debugging is unlocked only with a cryptographic key
  • Leaving a test point or connector available for factory programming and failure analysis, even if the debug port is locked afterward

Plan this early. It affects your manufacturing process and how you’ll analyze returned units.

Debugging goes hand in hand with good firmware structure. Short interrupt handlers (how to write an ISR in C), explicit state (state machines in embedded C) and correct use of volatile (the volatile keyword in embedded C) prevent many of the bugs you’d otherwise be hunting with a probe. When you need to read what the compiler generated, assembly language programming for embedded systems is the next step.

The complete guide to firmware programming

Embedded Firmware Development: Core Programming Concepts
Read the guide

Keep exploring

Guides from other topics

All topics →