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 Jul 29, 2020
1 parent 15aa2cd commit 87d9615
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 11 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
41 changes: 30 additions & 11 deletions src/spi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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()
Expand All @@ -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<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 87d9615

Please sign in to comment.