defmt provides structured binary logging for no_std firmware, where there is no standard output mechanism. Instead of formatting a message on the device, it emits a token referencing a format string in the ELF binary, together with the raw arguments. A host decoder reconstructs the message. This keeps core::fmt formatting code out of the firmware and makes log calls cheaper than a write!-based equivalent. section 6.2 section 6.3
The logging API produces frames but does not transmit them. Link exactly one transport crate: defmt-rtt for RTT on real hardware, defmt-itm for SWO, or defmt-semihosting for emulators. Linking two transports causes a link error. Semihosting traps into the debugger on each call and is too slow for real hardware. section 6.3.2
#![no_std]
#![no_main]
use cortex_m as _;
use cortex_m_rt::entry;
use defmt::info;
use defmt_rtt as _;
use panic_probe as _;
#[entry]
fn main() -> ! {
loop {
info!("Structured log from defmt");
// ~1 second pause at the 8 MHz HSI default clock.
cortex_m::asm::delay(8_000_000);
}
}
This minimal Cortex-M program registers defmt-rtt and emits an info message in a loop. The transport import is separate from the logging macro. section 6.3.1
[profile.release]
debug = 2
[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"] }
The dependencies include panic-probe with print-defmt to route panic messages through the registered transport. Without a print feature, panic-probe signals failure but discards the message. Release debug information lets probe-rs display source locations. section 6.3.1
[target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "probe-rs run --chip STM32F103C8Tx" rustflags = [ "-C", "link-arg=-Tlink.x", "-C", "link-arg=-Tdefmt.x", ] [build] target = "thumbv7m-none-eabi" # probe-rs filters defmt output by this variable. Without it, # defmt frames are received over RTT but nothing is printed. [env] DEFMT_LOG = "info"
This configuration selects a probe-rs runner, passes the linker scripts, and sets DEFMT_LOG to info. Without the filter variable, probe-rs receives the RTT frames but prints nothing. Transport build scripts set up the metadata section; normally no extra memory.x changes are needed. section 6.3.3
A host decoder such as probe-rs or cargo-embed displays the reconstructed messages. Compared with semihosting, compact RTT output is less intrusive and can be used frequently in performance-critical code. section 6.7 section 2.6.3
