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

Use type-safe enum for baud rate computation #1

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
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
39 changes: 28 additions & 11 deletions src/spi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use core::ptr;

use crate::hal::spi::FullDuplex;
pub use crate::hal::spi::{Mode, Phase, Polarity};
use crate::stm32::spi1;
use crate::stm32::{SPI1, SPI2, SPI3};
use nb;

Expand Down Expand Up @@ -114,6 +115,21 @@ pub struct Spi<SPI, PINS> {
pins: PINS,
}

#[inline]
fn compute_clock_variant(clocks: Hertz, freq: Hertz) -> spi1::cr1::BR_A {
match clocks.0 / freq.0 {
0 => unreachable!(),
1..=2 => spi1::cr1::BR_A::DIV2,
3..=5 => spi1::cr1::BR_A::DIV4,
6..=11 => spi1::cr1::BR_A::DIV8,
12..=23 => spi1::cr1::BR_A::DIV16,
24..=39 => spi1::cr1::BR_A::DIV32,
40..=95 => spi1::cr1::BR_A::DIV64,
96..=191 => spi1::cr1::BR_A::DIV128,
_ => spi1::cr1::BR_A::DIV256,
}
}

macro_rules! hal {
($($SPIX:ident: ($spiX:ident, $APBX:ident, $spiXen:ident, $spiXrst:ident, $pclkX:ident),)+) => {
$(
Expand Down Expand Up @@ -167,17 +183,7 @@ macro_rules! hal {
Polarity::IdleHigh => w.cpol().idle_high(),
};

match clocks.$pclkX().0 / freq.into().0 {
0 => unreachable!(),
1..=2 => w.br().div2(),
3..=5 => w.br().div4(),
6..=11 => w.br().div8(),
12..=23 => w.br().div16(),
24..=39 => w.br().div32(),
40..=95 => w.br().div64(),
96..=191 => w.br().div128(),
_ => w.br().div256(),
};
w.br().variant(compute_clock_variant(clocks.$pclkX(), freq.into()));

w.spe()
.enabled()
Expand All @@ -200,6 +206,17 @@ macro_rules! hal {
pub fn free(self) -> ($SPIX, (SCK, MISO, MOSI)) {
(self.spi, self.pins)
}

pub fn reclock<F>(&mut self, freq: F, clocks: Clocks)
where F: Into<Hertz>
{
self.spi.cr1.modify(|_, w| w.spe().disabled());
self.spi.cr1.modify(|_, w| {
w.br().variant(compute_clock_variant(clocks.$pclkX(), freq.into()));
w.spe().enabled()
});
}

}

impl<PINS> FullDuplex<u8> for Spi<$SPIX, PINS> {
Expand Down