Skip to content

Commit 20c51f1

Browse files
authored
Merge pull request #98 from ceigel/master
Add reclock functionality for SPI
2 parents 15aa2cd + 87d9615 commit 20c51f1

File tree

2 files changed

+33
-11
lines changed

2 files changed

+33
-11
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
77

88
## [Unreleased]
99

10+
### Added
11+
- SPI support for reclock after initialization ([#98](https://github.com/stm32-rs/stm32f3xx-hal/pull/98))
12+
1013
## [v0.5.0] - 2020-07-21
1114

1215
### Added

src/spi.rs

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use core::ptr;
55
use crate::hal::spi::FullDuplex;
66
pub use crate::hal::spi::{Mode, Phase, Polarity};
77
use crate::pac::{SPI1, SPI2, SPI3};
8+
use crate::stm32::spi1;
89

910
use crate::gpio::gpioa::{PA5, PA6, PA7};
1011
#[cfg(any(
@@ -162,17 +163,7 @@ macro_rules! hal {
162163
Polarity::IdleHigh => w.cpol().idle_high(),
163164
};
164165

165-
match clocks.$pclkX().0 / freq.into().0 {
166-
0 => unreachable!(),
167-
1..=2 => w.br().div2(),
168-
3..=5 => w.br().div4(),
169-
6..=11 => w.br().div8(),
170-
12..=23 => w.br().div16(),
171-
24..=39 => w.br().div32(),
172-
40..=95 => w.br().div64(),
173-
96..=191 => w.br().div128(),
174-
_ => w.br().div256(),
175-
};
166+
w.br().variant(Self::compute_baud_rate(clocks.$pclkX(), freq.into()));
176167

177168
w.spe()
178169
.enabled()
@@ -195,6 +186,34 @@ macro_rules! hal {
195186
pub fn free(self) -> ($SPIX, (SCK, MISO, MOSI)) {
196187
(self.spi, self.pins)
197188
}
189+
190+
/// Change the baud rate of the SPI
191+
pub fn reclock<F>(&mut self, freq: F, clocks: Clocks)
192+
where F: Into<Hertz>
193+
{
194+
self.spi.cr1.modify(|_, w| w.spe().disabled());
195+
self.spi.cr1.modify(|_, w| {
196+
w.br().variant(Self::compute_baud_rate(clocks.$pclkX(), freq.into()));
197+
w.spe().enabled()
198+
});
199+
}
200+
201+
fn compute_baud_rate(clocks: Hertz, freq: Hertz) -> spi1::cr1::BR_A {
202+
use spi1::cr1::BR_A;
203+
match clocks.0 / freq.0 {
204+
0 => unreachable!(),
205+
1..=2 => BR_A::DIV2,
206+
3..=5 => BR_A::DIV4,
207+
6..=11 => BR_A::DIV8,
208+
12..=23 => BR_A::DIV16,
209+
24..=39 => BR_A::DIV32,
210+
40..=95 => BR_A::DIV64,
211+
96..=191 => BR_A::DIV128,
212+
_ => BR_A::DIV256,
213+
}
214+
}
215+
216+
198217
}
199218

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

0 commit comments

Comments
 (0)