Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UsartSpi Support #588

Open
wants to merge 29 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4a110c9
Inital implimentation. Adds in on USART0 only.
CoolSlimbo Jun 23, 2024
8ac3a86
Implimented atmega328p support. Also untested, because I don't have a…
CoolSlimbo Jun 23, 2024
2cd0cbd
Reoragnise the `usart_spi` into its own module. + Docs
CoolSlimbo Jun 23, 2024
82ad09a
Rejig the docs.
CoolSlimbo Jun 23, 2024
ab5fad0
Atmega1280 and 2560 UsartSpi Implimentations
CoolSlimbo Jun 23, 2024
5debde9
Add 48p Normal Usart, idk what it was missing
CoolSlimbo Jun 23, 2024
a37cbc2
Added some more.
CoolSlimbo Jun 23, 2024
c5b076f
Fixed issue regarding CI.
CoolSlimbo Jun 23, 2024
9ddb92b
Mark bit writes as unsafe.
CoolSlimbo Jun 23, 2024
b88cf04
Optimise my laziness (remove the inital implimentation, only macros f…
CoolSlimbo Jun 24, 2024
d9bfd46
Finalise the remaining USART's (turns out I was right at the end). In…
CoolSlimbo Jun 24, 2024
597b073
Added some docs to make it less confusing.
CoolSlimbo Jun 27, 2024
54990d0
I haven't tested this because my atmega2560 is currently soldered and…
CoolSlimbo Jun 27, 2024
46f4183
Adjust example to properly run.
CoolSlimbo Jul 24, 2024
893f775
Merge branch 'Rahix:main' into main
CoolSlimbo Jul 26, 2024
8fa453f
Update avr-hal-generic/src/usart_spi.rs w/ armandas clock rates
CoolSlimbo Jul 26, 2024
3593202
Add dummy pin (figure out how to dynamic it)
CoolSlimbo Jul 26, 2024
0f0c38c
Merge branch 'main' of https://github.com/CoolSlimbo/avr-hal
CoolSlimbo Jul 26, 2024
7b21e5c
Seriously... how do I do dynamic tho?
CoolSlimbo Jul 26, 2024
0b020f5
Fix CS issue.
armandas Oct 4, 2024
b40ca48
Add a separate constructor for USART based SPI.
armandas Oct 4, 2024
5a01f72
Fix examples.
armandas Oct 4, 2024
c10cc13
Fix clippy warnings.
armandas Oct 4, 2024
7fec2a5
Fix typos
armandas Oct 4, 2024
2db4a18
Fix doc
armandas Oct 4, 2024
d4acdd6
Update comments to address feedback in #562
armandas Oct 5, 2024
bc67b95
Fix build error in for atmega1284p.
armandas Oct 10, 2024
c96666a
Add example, as per #591
armandas Oct 12, 2024
6f5a719
Update example link.
armandas Oct 14, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions avr-hal-generic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub mod port;
pub mod simple_pwm;
pub mod spi;
pub mod usart;
pub mod usart_spi;
pub mod wdt;

/// Prelude containing all HAL traits
Expand Down
38 changes: 37 additions & 1 deletion avr-hal-generic/src/spi.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! SPI Implementation
use crate::port;
use crate::{port, usart::UsartOps};
use core::marker::PhantomData;
use embedded_hal::spi::{self, SpiBus};

Expand Down Expand Up @@ -200,6 +200,42 @@ pub struct Spi<H, SPI, SCLKPIN, MOSIPIN, MISOPIN, CSPIN> {
_h: PhantomData<H>,
}

impl<H, USART, SCLKPIN, MOSIPIN, MISOPIN, UsartSPIDummyPin>
Spi<H, USART, SCLKPIN, MOSIPIN, MISOPIN, UsartSPIDummyPin>
where
USART: SpiOps<H, SCLKPIN, MOSIPIN, MISOPIN, UsartSPIDummyPin>
+ UsartOps<H, port::Pin<port::mode::Input, MISOPIN>, port::Pin<port::mode::Output, MOSIPIN>>,
SCLKPIN: port::PinOps,
MOSIPIN: port::PinOps,
MISOPIN: port::PinOps,
{
/// Instantiate a USART based SPI with the registers, SCLK/MOSI/MISO pins, and settings,
/// with the internal pull-up enabled on the MISO pin.
///
/// The pins are not actually used directly, but they are moved into the struct in
/// order to enforce that they are in the correct mode, and cannot be used by anyone
/// else while SPI is active.
pub fn new_from_usart(
p: USART,
sclk: port::Pin<port::mode::Output, SCLKPIN>,
mosi: port::Pin<port::mode::Output, MOSIPIN>,
miso: port::Pin<port::mode::Input<port::mode::PullUp>, MISOPIN>,
settings: Settings,
) -> Self {
let mut spi = Self {
p,
sclk,
mosi,
miso: miso.forget_imode(),
write_in_progress: false,
_cs: PhantomData,
_h: PhantomData,
};
spi.p.raw_setup(&settings);
spi
}
}

impl<H, SPI, SCLKPIN, MOSIPIN, MISOPIN, CSPIN> Spi<H, SPI, SCLKPIN, MOSIPIN, MISOPIN, CSPIN>
where
SPI: SpiOps<H, SCLKPIN, MOSIPIN, MISOPIN, CSPIN>,
Expand Down
132 changes: 132 additions & 0 deletions avr-hal-generic/src/usart_spi.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
//! MSPIM Implimentation
use crate::{port::PinOps, spi};

// This module just implements a macro for SpiOps, since underlyingly, the Spi type can still be used since it just needs SpiOps

/// Dummy Pin for MPSPIM
pub struct UsartSPIDummyPin;

impl PinOps for UsartSPIDummyPin {
type Dynamic = Self;

fn into_dynamic(self) -> Self::Dynamic {
self
}

unsafe fn out_set(&mut self) {}

unsafe fn out_clear(&mut self) {}

unsafe fn out_toggle(&mut self) {}

unsafe fn out_get(&self) -> bool {
false
}

unsafe fn in_get(&self) -> bool {
true
}

unsafe fn make_output(&mut self) {}

unsafe fn make_input(&mut self, _pull_up: bool) {}
}

pub type UsartSpi<H, USART, SCLKPIN, MOSIPIN, MISOPIN> =
spi::Spi<H, USART, SCLKPIN, MOSIPIN, MISOPIN, UsartSPIDummyPin>;

// Implement SpiOps trait for USART
#[macro_export]
macro_rules! add_usart_spi {
(
hal: $HAL:ty,
peripheral: $USART_SPI:ty,
register_suffix: $n:expr,
sclk: $sclkpin:ty,
mosi: $mosipin:ty,
miso: $misopin:ty,
) => {
$crate::paste::paste! {
// This is quite a messy way to get the doc string working properly... but it works!
#[doc = concat!("**Clock:** `", stringify!($sclkpin), "`<br>**MOSI:** `", stringify!($mosipin), "`<br> **MISO:** `", stringify!($misopin), "`")]
pub type [<Usart $n Spi>] = avr_hal_generic::usart_spi::UsartSpi<$HAL, $USART_SPI, $sclkpin, $mosipin, $misopin>;

impl $crate::spi::SpiOps<$HAL, $sclkpin, $mosipin, $misopin, $crate::usart_spi::UsartSPIDummyPin> for $USART_SPI {
fn raw_setup(&mut self, settings: &$crate::spi::Settings) {
use $crate::hal::spi;

// UBRRn must be zero at the time the transmitter is enabled.
self.[<ubrr $n>].write(|w| unsafe {w.bits(0)});

// We have to translate the character size register into the 2 bits which are the MSB/LSB and the phase
// 5 Bit Char = MSB and 1st
// 6 Bit Char = MSB and 2nd
// 7 Bit Char = LSB and 1st
// 8 Bit Char = LSB and 2nd
self.[<ucsr $n c>].write(|w| {
w.[<umsel $n>]().spi_master();

match settings.data_order {
$crate::spi::DataOrder::MostSignificantFirst => match settings.mode.phase {
spi::Phase::CaptureOnFirstTransition => w.[<ucsz $n>]().chr5(),
spi::Phase::CaptureOnSecondTransition => w.[<ucsz $n>]().chr6(),
},
$crate::spi::DataOrder::LeastSignificantFirst => match settings.mode.phase {
spi::Phase::CaptureOnFirstTransition => w.[<ucsz $n>]().chr7(),
spi::Phase::CaptureOnSecondTransition => w.[<ucsz $n>]().chr8(),
},
};

match settings.mode.polarity {
spi::Polarity::IdleLow => w.[<ucpol $n>]().clear_bit(),
spi::Polarity::IdleHigh => w.[<ucpol $n>]().set_bit(),
}
});

// Enable receiver and transmitter.
self.[<ucsr $n b>].write(|w| w
.[<txen $n>]().set_bit()
.[<rxen $n>]().set_bit()
);

// Set the clock divider for SPI clock.
// This must be done after the transmitter is enabled.
self.[<ubrr $n>].write(|w| unsafe {
match settings.clock {
$crate::spi::SerialClockRate::OscfOver2 => w.bits(0),
$crate::spi::SerialClockRate::OscfOver4 => w.bits(1),
$crate::spi::SerialClockRate::OscfOver8 => w.bits(3),
$crate::spi::SerialClockRate::OscfOver16 => w.bits(7),
$crate::spi::SerialClockRate::OscfOver32 => w.bits(15),
$crate::spi::SerialClockRate::OscfOver64 => w.bits(31),
$crate::spi::SerialClockRate::OscfOver128 => w.bits(63),
}
});
}

fn raw_release(&mut self) {
self.[<ucsr $n c>].write(|w| w.[<umsel $n>]().usart_async());
self.[<ucsr $n b>].reset();
}

fn raw_check_iflag(&self) -> bool {
self.[<ucsr $n a>].read().[<rxc $n>]().bit_is_set()
}

fn raw_read(&self) -> u8 {
self.[<udr $n>].read().bits()
}

fn raw_write(&mut self, byte: u8) {
self.[<udr $n>].write(|w| unsafe { w.bits(byte) });
}

fn raw_transaction(&mut self, byte: u8) -> u8 {
self.raw_write(byte);
while !self.raw_check_iflag() {}
self.raw_read()
}
}
}
};
}
75 changes: 75 additions & 0 deletions examples/atmega2560/src/bin/atmega2560-usart_spi-feedback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! This example demonstrates how to set up a SPI interface and communicate
//! over it. The physical hardware configuration consists of connecting a
//! jumper directly from pin `PB2` to pin `PB3`.
//!
//! Run the program using `cargo run`.
//! You should see it output the line `data: 42` repeatedly.
//! If the output you see is `data: 255`, you may need to check your jumper.

#![no_std]
#![no_main]

use atmega_hal::delay::Delay;
use atmega_hal::usart::{Baudrate, Usart};
use atmega_hal::usart_spi;
use embedded_hal::delay::DelayNs;
use embedded_hal::spi::SpiBus;
use panic_halt as _;

// Define core clock. This can be used in the rest of the project.
type CoreClock = atmega_hal::clock::MHz16;

#[avr_device::entry]
fn main() -> ! {
let dp = atmega_hal::Peripherals::take().unwrap();
let pins = atmega_hal::pins!(dp);

let mut delay = Delay::<crate::CoreClock>::new();

// set up serial interface for text output
let mut serial = Usart::new(
dp.USART0,
pins.pe0,
pins.pe1.into_output(),
Baudrate::<crate::CoreClock>::new(57600),
);

// Create SPI interface.
let mut spi = usart_spi::Usart1Spi::new_from_usart(
dp.USART1,
pins.pd5.into_output(),
pins.pd3.into_output(),
pins.pd2.into_pull_up_input(),
atmega_hal::spi::Settings::default(),
);

// Other SPI examples for other USART's

// let mut spi = usart_spi::Usart2Spi::new_from_usart(
// dp.USART2,
// pins.ph2.into_output(),
// pins.ph1.into_output(),
// pins.ph0.into_pull_up_input(),
// atmega_hal::spi::Settings::default(),
// );

// let mut spi = usart_spi::Usart3Spi::new_from_usart(
// dp.USART3,
// pins.pj2.into_output(),
// pins.pj1.into_output(),
// pins.pj0.into_pull_up_input(),
// atmega_hal::spi::Settings::default(),
// );

loop {
// Send a byte
let data_out: [u8; 1] = [42];
let mut data_in: [u8; 1] = [0];
// Send a byte
// Because MISO is connected to MOSI, the read data should be the same
spi.transfer(&mut data_in, &data_out).unwrap();

ufmt::uwriteln!(&mut serial, "data: {}\r", data_in[0]).unwrap();
delay.delay_ms(1000);
}
}
3 changes: 3 additions & 0 deletions mcu/atmega-hal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ pub mod eeprom;
#[cfg(feature = "device-selected")]
pub use eeprom::Eeprom;

#[cfg(feature = "device-selected")]
pub mod usart_spi;

pub struct Atmega;

#[cfg(any(feature = "atmega48p", feature = "atmega168", feature = "atmega328p"))]
Expand Down
6 changes: 4 additions & 2 deletions mcu/atmega-hal/src/usart.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ pub type UsartReader<USART, RX, TX, CLOCK> =
feature = "atmega328p",
feature = "atmega328pb",
feature = "atmega1284p",
feature = "atmega164pa"
feature = "atmega164pa",
feature = "atmega48p"
))]
pub type Usart0<CLOCK> = Usart<
crate::pac::USART0,
Expand All @@ -27,7 +28,8 @@ pub type Usart0<CLOCK> = Usart<
feature = "atmega328p",
feature = "atmega328pb",
feature = "atmega1284p",
feature = "atmega164pa"
feature = "atmega164pa",
feature = "atmega48p"
))]
avr_hal_generic::impl_usart_traditional! {
hal: crate::Atmega,
Expand Down
Loading