Skip to content

Commit

Permalink
Add reclock functionality for SPI
Browse files Browse the repository at this point in the history
  • Loading branch information
ceigel committed May 13, 2020
1 parent a73d1c2 commit d1a79a0
Showing 1 changed file with 30 additions and 11 deletions.
41 changes: 30 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 @@ -167,17 +168,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(Self::compute_baud_rate(clocks.$pclkX(), freq.into()));

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

/// Change the baud rate of the SPI
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(Self::compute_baud_rate(clocks.$pclkX(), freq.into()));
w.spe().enabled()
});
}

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


}

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

0 comments on commit d1a79a0

Please sign in to comment.