Stm32-hal2 borrow problem

Taking some baby steps in rust, and on UART communications on the pins of my stm32l476 (nucleo board) using stm32-hal2 crate.
UART signals look fine, but I now want to invert the tx pin, and run in these problems:

    // Problem 1: it doesn't write the bit ...
    defmt::info!("txinv: {:?}",;
    dp.USART1.cr2.modify(|_, w| w.txinv().set_bit());
    defmt::info!("txinv: {:?}",;

    // Problem 2: it doesn't write the u32 ...
    defmt::info!("cr2.bits {:?}",;
    dp.USART1.cr2.write(|w| unsafe { w.bits(0x11223344) });
    defmt::info!("cr2.bits {:?}",;

    // Set up the USART1 peripheral.
    let mut uart = Usart::new(
        dp.USART1, // <---- this moves USART1 <--------

    // Problem 3 what I really want is this, but errors with "borrowed after move"
    // (Plus - possibly - the indication from above, that it doesn't work)
    // dp.USART1.cr2.modify(|_, w| w.txinv().set_bit()); 

Any suggestions greatly appreciated

@tpilt, I don't know your chip at all, so I probably can't help that much. But I can take an educated guess.

Setting txinv probably doesn't work until the peripheral is initialized in some way. The Usart::new function probably does this. But as you saw, the Usart type takes ownership of the USART register block. To access the txinv bit, you'll need support from your HAL.

Just out of curiosity, why are you using stm32-hal2? It looks like there's also stm32l4xxx-hal. I took a look at both, but I don't see anything about txinv in either crate.

Also, you mentioned SPI in the text of your post, but you're setting up a UART peripheral. Why is that?

You might want to ask on the Matrix channel as well. It might be more active.

UART vs SPI - yes I edited that , but you were faster :slight_smile:

Isn't there a ninja-unsafe way of accessing the dp.USART1 even if it is borrowed away?
Just for the sake of nok cloning the HAL, and running from a fork.
(It's not for work ... only for play!)

Should I investigate the make_globals! / access_globals! patterns ?


Isn't there a ninja-unsafe way of accessing the dp.USART1 even if it is borrowed away?

Only if your HAL provides one. The Usart struct takes ownership of the USART register block precisely to prevent users from modifying registers and potentially invalidating invariants of the HAL abstraction. But in atsamd-hal, for example, we also provide an unsafe way to get a reference to the register block. I'm not sure if your HAL does that.

I'm not familiar with either of those macros.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.