From 87d9615332c4872709f9d54910904941da4d5a6d 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 --- CHANGELOG.md | 3 +++ src/spi.rs | 41 ++++++++++++++++++++++++++++++----------- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b36c5723..3650dca56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] +### Added +- SPI support for reclock after initialization ([#98](https://github.com/stm32-rs/stm32f3xx-hal/pull/98)) + ## [v0.5.0] - 2020-07-21 ### Added 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> {