How do I convert u32 data to &str in an embedded platform?

Viewed 2806

I want to convert u32 integer data to string in embedded Rust, but the problem is in embedded we can't use std code, so is there any way to do this?

let mut dist = ((elapsed as f32 / mono_timer.frequency().0 as f32 * 1e6) / 2.0) / 29.1;
let dist = dist as u32;
let data = String::from("data:");
data.push_str(dist);
1 Answers

answer found

use core::fmt::Write;
use heapless::String;
use heapless::consts::*;

fn foo(){
    let dist = 100u32;
    let mut data = String::<U32>::from("data:");
    
    // `write` for `heapless::String` returns an error if the buffer is full,
    // but because the buffer here is 32 bytes large,the u32 will fit with a 
    //lot 
    // of space left.
    let _=write!(data,"{}", dist);
}
Related