简体   繁体   中英

How do I configure a UART in Rust using the embedded HAL?

Background: I'm using the Nucleo-G071RB dev board. I'm new to rust, and working through some of the examples from the embedded HAL.

I was able to get this example up and running, but ran into some difficulty when trying to change the baudrate (links are to commit at head of master at the time of this writing): https://github.com/stm32-rs/stm32g0xx-hal/blob/116ac758cc50f4e1bfb9270d41403eac462cd791/examples/uart.rs

I found the default function referenced in the example: https://github.com/stm32-rs/stm32g0xx-hal/blob/116ac758cc50f4e1bfb9270d41403eac462cd791/src/serial.rs#L112

So I tried to make something similar:

fn uart_cfg() -> serial::Config {
    let baudrate = 115_200.bps();
    serial::Config {
        baudrate,
        wordlength: serial::WordLength::DataBits8,
        parity: serial::Parity::ParityNone,
        stopbits: serial::StopBits::STOP1,
    }
}

This gave me:

error[E0451]: field `baudrate` of struct `hal::serial::Config` is private
  --> src/main.rs:22:9
   |
22 |         baudrate,
   |         ^^^^^^^^ field `baudrate` is private

(repeated errors omitted).

How do I set the baudrate on the UART periferal cleanly?

I ended up with this line:

let cfg = serial::Config::default().baudrate(115_200.bps());

And used it in my hello world:

#[entry]
fn main() -> ! {
    let dp = stm32::Peripherals::take().expect("cannot take peripherals");
    let mut rcc = dp.RCC.constrain();

    let gpioa = dp.GPIOA.split(&mut rcc);
    let cfg = serial::Config::default().baudrate(115_200.bps());
    let mut usart2 = dp
        .USART2
        .usart(gpioa.pa2, gpioa.pa3, cfg, &mut rcc)
        .unwrap();

    let mut delay = dp.TIM15.delay(&mut rcc);

    loop {
        writeln!(usart2, "Hello, World!").unwrap();
        delay.delay(50.ms());
    }
}

This runs into trouble if you want to define the config once and use it for multiple UARTS. Eg:

#[entry]
fn main() -> ! {
    let dp = stm32::Peripherals::take().expect("cannot take peripherals");
    let mut rcc = dp.RCC.constrain();

    let cfg = serial::Config::default().baudrate(115_200.bps());

    let gpioa = dp.GPIOA.split(&mut rcc);
    let mut usart2 = dp
        .USART2
        .usart(gpioa.pa2, gpioa.pa3, cfg, &mut rcc)
        .unwrap();

    let gpiob = dp.GPIOB.split(&mut rcc);
    let mut usart3 = dp
        .USART3
        .usart(gpiob.pb10, gpiob.pb11, cfg, &mut rcc)
        .unwrap();

    let mut delay = dp.TIM15.delay(&mut rcc);

    loop {
        writeln!(usart2, "Hello, World!").unwrap();
        writeln!(usart3, "Hello, again!").unwrap();
        delay.delay(50.ms());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM