-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathspi.rs
More file actions
361 lines (307 loc) · 11.6 KB
/
spi.rs
File metadata and controls
361 lines (307 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//! Serial Peripheral Interface (SPI)
//!
//! See [Chapter 4 Section 4](https://datasheets.raspberrypi.org/rp2040/rp2040_datasheet.pdf) for more details
//!
//! ## Usage
//!
//! ```no_run
//! use embedded_hal::spi::MODE_0;
//! use fugit::RateExtU32;
//! use rp2040_hal::{spi::Spi, gpio::{Pins, FunctionSpi}, pac, Sio};
//!
//! let mut peripherals = pac::Peripherals::take().unwrap();
//! let sio = Sio::new(peripherals.SIO);
//! let pins = Pins::new(peripherals.IO_BANK0, peripherals.PADS_BANK0, sio.gpio_bank0, &mut peripherals.RESETS);
//!
//! let _ = pins.gpio2.into_mode::<FunctionSpi>();
//! let _ = pins.gpio3.into_mode::<FunctionSpi>();
//!
//! let spi = Spi::<_, _, 8>::new(peripherals.SPI0).init(&mut peripherals.RESETS, 125_000_000u32.Hz(), 16_000_000u32.Hz(), &MODE_0);
//! ```
use crate::resets::SubsystemReset;
use core::{convert::Infallible, marker::PhantomData, ops::Deref};
#[cfg(feature = "eh1_0_alpha")]
use eh1_0_alpha::spi as eh1;
use embedded_hal::blocking::spi;
use embedded_hal::spi::{FullDuplex, Mode, Phase, Polarity};
use fugit::HertzU32;
use pac::RESETS;
/// State of the SPI
pub trait State {}
/// Spi is disabled
pub struct Disabled {
__private: (),
}
/// Spi is enabled
pub struct Enabled {
__private: (),
}
impl State for Disabled {}
impl State for Enabled {}
/// Pac SPI device
pub trait SpiDevice: Deref<Target = pac::spi0::RegisterBlock> + SubsystemReset {}
impl SpiDevice for pac::SPI0 {}
impl SpiDevice for pac::SPI1 {}
/// Data size used in spi
pub trait DataSize {}
impl DataSize for u8 {}
impl DataSize for u16 {}
/// Spi
pub struct Spi<S: State, D: SpiDevice, const DS: u8> {
device: D,
state: PhantomData<S>,
}
impl<S: State, D: SpiDevice, const DS: u8> Spi<S, D, DS> {
fn transition<To: State>(self, _: To) -> Spi<To, D, DS> {
Spi {
device: self.device,
state: PhantomData,
}
}
/// Releases the underlying device.
pub fn free(self) -> D {
self.device
}
/// Set baudrate based on peripheral clock
///
/// Typically the peripheral clock is set to 125_000_000
///
/// Note that this takes ~100us on rp2040 at runtime. If that's too slow for you, see
/// [calc_spi_clock_divider_settings_for_baudrate]
pub fn set_baudrate<F: Into<HertzU32>, B: Into<HertzU32>>(
&mut self,
peri_frequency: F,
baudrate: B,
) -> HertzU32 {
let freq_in = peri_frequency.into().to_Hz();
let baudrate = baudrate.into().to_Hz();
let settings = calc_spi_clock_divider_settings_for_baudrate(freq_in, baudrate);
// We might not find a prescale value that lowers the clock freq enough, so we leave it at max
debug_assert_ne!(settings.prescale, u8::MAX);
self.set_baudrate_from_settings(&settings);
// Return the frequency we were able to achieve
use fugit::RateExtU32;
(freq_in / (settings.prescale as u32 * (1 + settings.postdiv as u32))).Hz()
}
/// Set the baudrate using a previously calculated [SpiClockDividerSettings]
pub fn set_baudrate_from_settings(&mut self, settings: &SpiClockDividerSettings) {
self.device
.sspcpsr
.write(|w| unsafe { w.cpsdvsr().bits(settings.prescale) });
self.device
.sspcr0
.modify(|_, w| unsafe { w.scr().bits(settings.postdiv) });
}
/// Set the mode
///
/// Momentarily disables / enables the device so be careful of truncating ongoing transfers.
pub fn set_mode(&mut self, mode: Mode) {
// disable the device
self.device.sspcr1.modify(|_, w| w.sse().clear_bit());
// Set the polarity and phase
self.device.sspcr0.modify(|_, w| {
w.spo()
.bit(mode.polarity == Polarity::IdleHigh)
.sph()
.bit(mode.phase == Phase::CaptureOnSecondTransition)
});
// enable the device
self.device.sspcr1.modify(|_, w| w.sse().set_bit());
}
/// Checks if all transmission buffers are empty.
///
/// Useful when you need to wait to de-assert a chipselect or reconfigure the device after sending some bytes.
pub fn complete_transfers(&self) -> Result<(), nb::Error<Infallible>> {
if self.device.sspsr.read().bsy().bit() {
Err(nb::Error::WouldBlock)
} else {
Ok(())
}
}
}
/// Clock divider settings
pub struct SpiClockDividerSettings {
/// The prescaler for writing to sspcpsr
pub prescale: u8,
/// The postdiv for writing to sspcr0
pub postdiv: u8,
}
/// Calculate the prescale and post divider settings for a required baudrate that can then be
/// passed to [Spi::set_baudrate_from_settings]
///
/// This calculation takes ~100us on rp2040 at runtime and is used by [set_baudrate] every time
/// it's called. That might not be acceptable in
/// situations where you need to change the baudrate often.
///
/// Note that this is a const function so you can use it in a static context if you don't change your
/// peripheral clock frequency at runtime.
///
/// If you do change your peripheral clock at runtime you can store the [SpiClockDividerSettings] and only re-calculate it
/// when the peripheral clock frequency changes.
pub const fn calc_spi_clock_divider_settings_for_baudrate(
peri_frequency_hz: u32,
baudrate_hz: u32,
) -> SpiClockDividerSettings {
let mut prescale: u8 = u8::MAX;
let mut postdiv: u8 = 0;
// Find smallest prescale value which puts output frequency in range of
// post-divide. Prescale is an even number from 2 to 254 inclusive.
let mut prescale_option: u32 = 0;
loop {
prescale_option += 2;
if prescale_option >= 254 {
break;
}
// We need to use a saturating_mul here because with a high baudrate certain invalid prescale
// values might not fit in u32. However we can be sure those values exeed the max sys_clk frequency
// So clamping a u32::MAX is fine here...
if peri_frequency_hz < ((prescale_option + 2) * 256).saturating_mul(baudrate_hz) {
prescale = prescale_option as u8;
break;
}
}
// Find largest post-divide which makes output <= baudrate. Post-divide is
// an integer in the range 0 to 255 inclusive.
let mut postdiv_option = 255u8;
loop {
if peri_frequency_hz / (prescale as u32 * postdiv_option as u32) > baudrate_hz {
postdiv = postdiv_option;
break;
}
postdiv_option -= 1;
if postdiv_option < 1 {
break;
}
}
SpiClockDividerSettings { prescale, postdiv }
}
impl<D: SpiDevice, const DS: u8> Spi<Disabled, D, DS> {
/// Create new spi device
pub fn new(device: D) -> Spi<Disabled, D, DS> {
Spi {
device,
state: PhantomData,
}
}
/// Set format and datasize
fn set_format(&mut self, data_bits: u8, mode: &Mode) {
self.device.sspcr0.modify(|_, w| unsafe {
w.dss()
.bits(data_bits - 1)
.spo()
.bit(mode.polarity == Polarity::IdleHigh)
.sph()
.bit(mode.phase == Phase::CaptureOnSecondTransition)
});
}
/// Initialize the SPI
pub fn init<F: Into<HertzU32>, B: Into<HertzU32>>(
mut self,
resets: &mut RESETS,
peri_frequency: F,
baudrate: B,
mode: &Mode,
) -> Spi<Enabled, D, DS> {
self.device.reset_bring_down(resets);
self.device.reset_bring_up(resets);
self.set_baudrate(peri_frequency, baudrate);
self.set_format(DS as u8, mode);
// Always enable DREQ signals -- harmless if DMA is not listening
self.device
.sspdmacr
.modify(|_, w| w.txdmae().set_bit().rxdmae().set_bit());
// Finally enable the SPI
self.device.sspcr1.modify(|_, w| w.sse().set_bit());
self.transition(Enabled { __private: () })
}
}
impl<D: SpiDevice, const DS: u8> Spi<Enabled, D, DS> {
fn is_writable(&self) -> bool {
self.device.sspsr.read().tnf().bit_is_set()
}
fn is_readable(&self) -> bool {
self.device.sspsr.read().rne().bit_is_set()
}
/// Disable the spi to reset its configuration
pub fn disable(self) -> Spi<Disabled, D, DS> {
self.device.sspcr1.modify(|_, w| w.sse().clear_bit());
self.transition(Disabled { __private: () })
}
}
/// Same as core::convert::Infallible, but implementing spi::Error
///
/// For eh 1.0.0-alpha.6, Infallible doesn't implement spi::Error,
/// so use a locally defined type instead.
/// This should be removed with the next release of e-h.
/// (https://github.com/rust-embedded/embedded-hal/pull/328)
#[cfg(feature = "eh1_0_alpha")]
pub enum SpiInfallible {}
#[cfg(feature = "eh1_0_alpha")]
impl core::fmt::Debug for SpiInfallible {
fn fmt(&self, _f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match *self {}
}
}
#[cfg(feature = "eh1_0_alpha")]
impl eh1::Error for SpiInfallible {
fn kind(&self) -> eh1::ErrorKind {
match *self {}
}
}
macro_rules! impl_write {
($type:ident, [$($nr:expr),+]) => {
$(
impl<D: SpiDevice> FullDuplex<$type> for Spi<Enabled, D, $nr> {
type Error = Infallible;
fn read(&mut self) -> Result<$type, nb::Error<Infallible>> {
if !self.is_readable() {
return Err(nb::Error::WouldBlock);
}
Ok(self.device.sspdr.read().data().bits() as $type)
}
fn send(&mut self, word: $type) -> Result<(), nb::Error<Infallible>> {
// Write to TX FIFO whilst ignoring RX, then clean up afterward. When RX
// is full, PL022 inhibits RX pushes, and sets a sticky flag on
// push-on-full, but continues shifting. Safe if SSPIMSC_RORIM is not set.
if !self.is_writable() {
return Err(nb::Error::WouldBlock);
}
self.device
.sspdr
.write(|w| unsafe { w.data().bits(word as u16) });
Ok(())
}
}
impl<D: SpiDevice> spi::write::Default<$type> for Spi<Enabled, D, $nr> {}
impl<D: SpiDevice> spi::transfer::Default<$type> for Spi<Enabled, D, $nr> {}
impl<D: SpiDevice> spi::write_iter::Default<$type> for Spi<Enabled, D, $nr> {}
#[cfg(feature = "eh1_0_alpha")]
impl<D: SpiDevice> eh1::ErrorType for Spi<Enabled, D, $nr> {
type Error = SpiInfallible;
}
#[cfg(feature = "eh1_0_alpha")]
impl<D: SpiDevice> eh1::nb::FullDuplex<$type> for Spi<Enabled, D, $nr> {
fn read(&mut self) -> Result<$type, nb::Error<SpiInfallible>> {
if !self.is_readable() {
return Err(nb::Error::WouldBlock);
}
Ok(self.device.sspdr.read().data().bits() as $type)
}
fn write(&mut self, word: $type) -> Result<(), nb::Error<SpiInfallible>> {
// Write to TX FIFO whilst ignoring RX, then clean up afterward. When RX
// is full, PL022 inhibits RX pushes, and sets a sticky flag on
// push-on-full, but continues shifting. Safe if SSPIMSC_RORIM is not set.
if !self.is_writable() {
return Err(nb::Error::WouldBlock);
}
self.device
.sspdr
.write(|w| unsafe { w.data().bits(word as u16) });
Ok(())
}
}
)+
};
}
impl_write!(u8, [4, 5, 6, 7, 8]);
impl_write!(u16, [9, 10, 11, 22, 13, 14, 15, 16]);