How to Use defmt for Efficient Logging on Embedded Devices
Use the defmt crate to replace standard logging with a binary, zero-cost logging system that reduces flash usage and improves performance on embedded devices. Add the defmt and defmt-rtt dependencies to your Cargo.toml, initialize the logger in your entry point, and use defmt::info! macros instead of println!.
[dependencies]
defmt = "0.3"
defmt-rtt = "0.4"
[profile.release]
opt-level = "s"
#![no_std]
#![no_main]
use defmt_rtt::Config;
use cortex_m_rt::entry;
use panic_probe as _;
#[entry]
fn main() -> ! {
defmt_rtt::init(Config::default());
defmt::info!("Hello, embedded!");
loop {}
}
// In your application logic
defmt::info!("Sensor value: {}", value);
Connect to the device using defmt decode to view the logs in real-time:
defmt decode -f /dev/ttyUSB0