Skip to content
systemcoding.dev
Embedded

Flash Rust Firmware With probe-rs run and Print Logs With defmt

Set probe-rs run as the Cargo runner, add defmt and defmt-rtt, and read log lines from a running Cortex-M board in your terminal with panic-probe.

6 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Rust, Arm and C logos.

A board with no display and no serial cable still talks to you if the debug probe carries the text. The usual way in embedded Rust is a pair of tools that fit together: probe-rs run flashes the ELF and then stays attached, and defmt formats log messages so cheaply that the chip sends only a small index and the raw arguments, leaving the text on your computer. This post wires both into a project so that cargo run flashes the board and prints INFO lines, with Rust 1.85, defmt 1.0, defmt-rtt 1.0, panic-probe 1.0 and probe-rs 0.27. It builds on blinking an LED with stm32f4xx-hal, and the same files work for any Cortex-M chip.

How the pieces fit

There are three separate jobs.

probe-rs is a host program that speaks to the debug probe (an ST-LINK, a CMSIS-DAP probe, a J-Link) and through it to the chip's debug port. It erases and programs flash, resets the core, and can read memory while the program runs. probe-rs run combines flashing with "attach and show output", which is why it works as a Cargo runner. The probe-rs documentation lists the supported chips and probes.

RTT, Real-Time Transfer, is a protocol from SEGGER. The firmware keeps a small control block in RAM that holds ring buffers. The probe reads those buffers over the debug port while the core runs, with no UART pins and no extra peripheral. defmt-rtt is the crate that puts defmt's output into an RTT up-channel.

defmt is the formatter. In defmt::info!("temp = {=u16}", t) the string literal is not stored in the firmware. The compiler interns it into the ELF file's .defmt section, which never gets flashed, and the chip sends only an integer that stands for the string plus the bytes of t. The host decodes it using the ELF it already has. The result is logging that costs far less flash and far fewer cycles than core::fmt.

The dependencies

Cargo.tomlTOML
[package]
name = "blinky-log"
version = "0.1.0"
edition = "2021"

[dependencies]
cortex-m = { version = "0.7", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7"
defmt = "1.0"
defmt-rtt = "1.0"
panic-probe = { version = "1.0", features = ["print-defmt"] }

[dependencies.stm32f4xx-hal]
version = "0.21"
features = ["stm32f411"]

[profile.release]
debug = 2
opt-level = "s"
lto = true

panic-probe with print-defmt makes a panic print its message through defmt and then execute a breakpoint, so probe-rs run sees the halt and exits. The critical-section-single-core feature on cortex-m gives defmt-rtt the critical section it needs to write from an interrupt and from main without tearing a message. On a multi-core chip you would pick a different implementation.

debug = 2 keeps full debug info in the ELF so that probe-rs can show file and line information beside each log line. It does not enlarge what the chip stores.

The Cargo configuration

.cargo/config.tomlTOML
[build]
target = "thumbv7em-none-eabihf"

[target.thumbv7em-none-eabihf]
runner = "probe-rs run --chip STM32F411RETx"
rustflags = [
  "-C", "link-arg=-Tlink.x",
  "-C", "link-arg=-Tdefmt.x",
]

[env]
DEFMT_LOG = "debug"

The second link argument, -Tdefmt.x, is easy to forget and is the most common reason logging does nothing. defmt.x is a linker script fragment that places the interned strings in the right section. Without it the linker emits a wall of undefined _defmt_* symbols or, worse, a binary with log lines that the host cannot decode.

DEFMT_LOG sets the compile-time level filter. Log macros below the level expand to nothing, so trace! calls in a release build cost no flash at all. The default, when the variable is unset, is error only, which makes people believe defmt is broken: info! lines are compiled out unless you raise the level.

A program that logs

src/main.rsrust
#![no_std]
#![no_main]

use cortex_m_rt::entry;
use defmt::{debug, info, warn};
use defmt_rtt as _;
use panic_probe as _;
use stm32f4xx_hal::{pac, prelude::*};

#[entry]
fn main() -> ! {
    let dp = pac::Peripherals::take().unwrap();
    let cp = cortex_m::Peripherals::take().unwrap();

    let rcc = dp.RCC.constrain();
    let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();
    info!("clocks frozen, sysclk = {} Hz", clocks.sysclk().to_Hz());

    let gpioa = dp.GPIOA.split();
    let mut led = gpioa.pa5.into_push_pull_output();
    let mut delay = cp.SYST.delay(&clocks);

    let mut count: u32 = 0;
    loop {
        led.toggle();
        count += 1;
        debug!("toggle number {}", count);
        if count == 3 {
            warn!("three toggles done, stopping");
            panic!("demo panic after {} toggles", count);
        }
        delay.delay_ms(500u32);
    }
}

use defmt_rtt as _; and use panic_probe as _; link the crates for their global effects: defmt-rtt registers the logger and panic-probe registers the panic handler. Neither exports anything you call. The format placeholders in defmt are {} for types that implement defmt::Format, and {=u16} style hints force a specific wire encoding, which is smaller than the default when you know the type.

Flash and read

Shell
cargo run --release

The runner flashes the board and attaches. A run of this program prints:

Text
INFO  clocks frozen, sysclk = 48000000 Hz
DEBUG toggle number 1
DEBUG toggle number 2
DEBUG toggle number 3
WARN  three toggles done, stopping
ERROR panicked at src/main.rs:30:13:
demo panic after 3 toggles

The exact line decoration (timestamps, the crate and file position in brackets) differs between probe-rs releases and options, so read it as the shape rather than the literal text. After the panic, panic-probe triggers a breakpoint and probe-rs run reports the halt and exits with a non-zero status, so a script or CI job notices the failure.

Timestamps and filtering

By default there is no timestamp, because the chip would have to supply one. If you want one, define it once anywhere in the firmware:

src/timestamp.rsrust
use core::sync::atomic::{AtomicU32, Ordering};

static COUNT: AtomicU32 = AtomicU32::new(0);

defmt::timestamp!("{=u32:us}", {
    // A monotonic counter: a real design reads a hardware timer instead.
    COUNT.fetch_add(1, Ordering::Relaxed)
});

Here the counter increments per message and is not a time at all, which is fine for ordering. Substitute a timer's microsecond count for real timestamps. Note that fetch_add needs an atomic read-modify-write, which a Cortex-M0 lacks, so use a critical section there.

Runtime filtering is separate: probe-rs run accepts --log-format for host-side decoration, and the compile-time DEFMT_LOG can name modules, as in DEFMT_LOG=warn,blinky_log::sensor=trace.

Common failures

SymptomCause
Error: no probe was foundthe probe is not connected, or udev rules block access on Linux
program runs, no log linesDEFMT_LOG unset, so info! compiled out, or -Tdefmt.x missing
garbled text or "malformed frame"the host decoded with a different ELF than the one flashed, so rebuild and rerun
Error: The chip could not be foundthe --chip name is wrong; probe-rs chip list prints valid names
first lines missingthe firmware wrote before the probe attached, since RTT buffers wrap

The last item is worth knowing. probe-rs run resets the target after flashing and attaches quickly, but messages written in the first microseconds can be overwritten if the ring buffer is small and the host is slow. In defmt-rtt the channel is blocking or non-blocking according to a Cargo feature, and the default is to drop old data rather than stall the core.

When defmt is the wrong choice

defmt needs the ELF on the host to decode, so you cannot read its output from a log file on a device in the field without storing the ELF alongside. For a production device that reports over a network, send your own structured messages. defmt is for development and for factory test, where a probe is attached. Output also goes only to the host side that understands defmt; a generic serial terminal shows binary.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.