Rahix / avr-hal

embedded-hal abstractions for AVR microcontrollers
Apache License 2.0
1.23k stars 216 forks source link

Utilising the `atmega2560`'s "USART in SPI Mode" #561

Open CoolSlimbo opened 1 week ago

CoolSlimbo commented 1 week ago

According the the atmega2560 datasheet, its USART modules can be used in "SPI Mode," which essentially gives an extra bus (or four) to add SPI devices to it. However, within the current implementation of avr_hal/atmega_hal, it's not plausible to use the USART modules in SPI mode.

Given this is hardware supported on the atmega's (versions of it), it would make sense to have a hardware implementation of it it in the HAL's.

Free to give this an attempt if given a suggestion in the right way for how to get started.


Related Issue:

Linked PR: #562

Rahix commented 1 week ago

Yes, this isn't supported yet.

If anyone is interested in working on a "USART as SPI" driver and needs guidance on how to do this, feel free to ping me!

CoolSlimbo commented 1 week ago

I'll gladly give this a shot in implementation, if you could aid a hand in the direction it needs to go in!

Currently, my confusion is just on how one would implement it, whilst also preventing usage of the USART for USART purposes.

Rahix commented 1 week ago

whilst also preventing usage of the USART for USART purposes.

This part is actually very simple. The UsartSpi driver constructor consumes the USART peripheral, just like the current UART driver consumes it. Due to Rust's ownership rules, this means only one of the two can ever exist:

    let dp = atmega_hal::Peripherals::take().unwrap();
    let pins = atmega_hal::pins!(dp);
    let mut serial = Usart::new(
        dp.USART0, // <- USART0 is moved into `serial` here
        pins.pe0,
        pins.pe1.into_output(),
        Baudrate::<crate::CoreClock>::new(57600),
    );

    let mut spi = UsartSpi::new(dp.USART0, ...);  // <- compiler error because USART0 was moved previously and is no longer available
Rahix commented 1 week ago

if you could aid a hand in the direction it needs to go in!

Generally, you'll need to add a usart_spi module in avr-hal-generic, similar in structure to the existing spi or usart modules. This defines the generic UsartSpi driver and a macro for the MCU-specific HALs. This macro is then instanciated in atmega-hal to implement USART as SPI for the available USART peripherals.

CoolSlimbo commented 1 week ago

Roger on that. I do see that now, I was over-engineering that way to much...

I'll get to work on implementing the driver, however, would this preferred to be in the USART or SPI module?

Rahix commented 1 week ago

I'd create a completely new module for USART as SPI. usart_spi I guess.