From 4de7882ca52b8088a718b4c4bdabf3f1840e7d88 Mon Sep 17 00:00:00 2001 From: Cristian Eigel Date: Thu, 23 Apr 2020 22:33:57 +0200 Subject: [PATCH] Add reclock functionality for SPI --- src/spi.rs | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/src/spi.rs b/src/spi.rs index b6d0e74e5..193d1fe55 100644 --- a/src/spi.rs +++ b/src/spi.rs @@ -5,6 +5,7 @@ use core::ptr; use crate::hal::spi::FullDuplex; pub use crate::hal::spi::{Mode, Phase, Polarity}; use crate::pac::{SPI1, SPI2, SPI3}; +use crate::stm32::spi1; use crate::gpio::gpioa::{PA5, PA6, PA7}; #[cfg(any( @@ -162,17 +163,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() @@ -195,6 +186,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(&mut self, freq: F, clocks: Clocks) + where F: Into + { + 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 FullDuplex for Spi<$SPIX, PINS> {