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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Serial Peripheral Interface (SPI) bus. Implements traits from `embedded-hal`.

// Based on `stm32l4xx-hal` and `stm32h7xx-hal`.

use core::ptr;

use embedded_hal::spi::{FullDuplex, Mode, Phase, Polarity};

use cfg_if::cfg_if;
use paste::paste;

use crate::{
    pac::{self, RCC},
    rcc_en_reset,
    traits::ClockCfg,
};

/// SPI error
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// Overrun occurred
    Overrun,
    /// Mode fault occurred
    ModeFault,
    /// CRC error
    Crc,
}

#[doc(hidden)]
mod private {
    pub trait Sealed {}
}

/// SCK pin. This trait is sealed and cannot be implemented.
pub trait SckPin<SPI>: private::Sealed {}
/// MISO pin. This trait is sealed and cannot be implemented.
pub trait MisoPin<SPI>: private::Sealed {}
/// MOSI pin. This trait is sealed and cannot be implemented.
pub trait MosiPin<SPI>: private::Sealed {}

// #[derive(Clone, Copy)]
// pub enum SpiDevice {
//     One,
//     Two,
//     Three,
// }

#[cfg(feature = "h7")]
#[derive(Copy, Clone)]
pub struct Config {
    mode: Mode,
    swap_miso_mosi: bool,
    cs_delay: f32,
    managed_cs: bool,
    suspend_when_inactive: bool,
    communication_mode: CommunicationMode,
}

#[cfg(feature = "h7")]
impl Config {
    /// Create a default configuration for the SPI interface.
    ///
    /// Arguments:
    /// * `mode` - The SPI mode to configure.
    pub fn new(mode: Mode) -> Self {
        Config {
            mode,
            swap_miso_mosi: false,
            cs_delay: 0.0,
            managed_cs: false,
            suspend_when_inactive: false,
            communication_mode: CommunicationMode::FullDuplex,
        }
    }

    /// Specify that the SPI MISO/MOSI lines are swapped.
    ///
    /// Note:
    /// * This function updates the HAL peripheral to treat the pin provided in the MISO parameter
    /// as the MOSI pin and the pin provided in the MOSI parameter as the MISO pin.
    pub fn swap_mosi_miso(mut self) -> Self {
        self.swap_miso_mosi = true;
        self
    }

    /// Specify a delay between CS assertion and the beginning of the SPI transaction.
    ///
    /// Note:
    /// * This function introduces a delay on SCK from the initiation of the transaction. The delay
    /// is specified as a number of SCK cycles, so the actual delay may vary.
    ///
    /// Arguments:
    /// * `delay` - The delay between CS assertion and the start of the transaction in seconds.
    /// register for the output pin.
    pub fn cs_delay(mut self, delay: f32) -> Self {
        self.cs_delay = delay;
        self
    }

    /// CS pin is automatically managed by the SPI peripheral.
    ///
    /// # Note
    /// SPI is configured in "endless transaction" mode, which means that the SPI CSn pin will
    /// assert when the first data is sent and will not de-assert.
    ///
    /// If CSn should be de-asserted between each data transfer, use `suspend_when_inactive()` as
    /// well.
    pub fn manage_cs(mut self) -> Self {
        self.managed_cs = true;
        self
    }

    /// Suspend a transaction automatically if data is not available in the FIFO.
    ///
    /// # Note
    /// This will de-assert CSn when no data is available for transmission and hardware is managing
    /// the CSn pin.
    pub fn suspend_when_inactive(mut self) -> Self {
        self.suspend_when_inactive = true;
        self
    }

    /// Select the communication mode of the SPI bus.
    pub fn communication_mode(mut self, mode: CommunicationMode) -> Self {
        self.communication_mode = mode;
        self
    }
}

#[cfg(feature = "h7")]
impl From<Mode> for Config {
    fn from(mode: Mode) -> Self {
        Self::new(mode)
    }
}

/// SPI peripheral operating in full duplex master mode
pub struct Spi<SPI> {
    spi: SPI,
}

macro_rules! hal {
    ($SPIX:ident, $spi:ident, $apb:expr) => {
        impl Spi<pac::$SPIX> { paste! {
            /// Configures the SPI peripheral to operate in full duplex master mode
            pub fn [<new_ $spi>]<C: ClockCfg>(
                spi: pac::$SPIX,
                mode: Mode,
                freq: u32,
                clocks: &C,
                rcc: &mut RCC,
            ) -> Self {

            rcc_en_reset!([<apb $apb>], $spi, rcc);
                cfg_if! {
                    if #[cfg(feature = "h7")] {
                          // Disable SS output
                        spi.cfg2.write(|w| w.ssoe().disabled());

                        let config: Config = config.into();

                        let spi_freq = freq;
                        let spi_ker_ck = match Self::kernel_clk(clocks) {
                            Some(ker_hz) => ker_hz.0,
                            _ => panic!("$SPIX kernel clock not running!")
                        };
                        let mbr = match spi_ker_ck / spi_freq {
                            0 => unreachable!(),
                            1..=2 => MBR::DIV2,
                            3..=5 => MBR::DIV4,
                            6..=11 => MBR::DIV8,
                            12..=23 => MBR::DIV16,
                            24..=47 => MBR::DIV32,
                            48..=95 => MBR::DIV64,
                            96..=191 => MBR::DIV128,
                            _ => MBR::DIV256,
                        };
                        spi.cfg1.modify(|_, w| {
                            w.mbr()
                                .variant(mbr) // master baud rate
                        });
                        spi!(DSIZE, spi, $TY); // modify CFG1 for DSIZE

                        // ssi: select slave = master mode
                        spi.cr1.write(|w| w.ssi().slave_not_selected());

                        // Calculate the CS->transaction cycle delay bits.
                        let (start_cycle_delay, interdata_cycle_delay) = {
                            let mut delay: u32 = (config.cs_delay * spi_freq as f32) as u32;

                            // If the cs-delay is specified as non-zero, add 1 to the delay cycles
                            // before truncation to an integer to ensure that we have at least as
                            // many cycles as required.
                            if config.cs_delay > 0.0_f32 {
                                delay += 1;
                            }

                            if delay > 0xF {
                                delay = 0xF;
                            }

                            // If CS suspends while data is inactive, we also require an
                            // "inter-data" delay.
                            if config.suspend_when_inactive {
                                (delay as u8, delay as u8)
                            } else {
                                (delay as u8, 0_u8)
                            }
                        };

                        // The calculated cycle delay may not be more than 4 bits wide for the
                        // configuration register.
                        let communication_mode = match config.communication_mode {
                            CommunicationMode::Transmitter => COMM::TRANSMITTER,
                            CommunicationMode::Receiver => COMM::RECEIVER,
                            CommunicationMode::FullDuplex => COMM::FULLDUPLEX,
                        };

                        // mstr: master configuration
                        // lsbfrst: MSB first
                        // comm: full-duplex
                        spi.cfg2.write(|w| {
                            w.cpha()
                                .bit(config.mode.phase ==
                                     Phase::CaptureOnSecondTransition)
                                .cpol()
                                .bit(config.mode.polarity == Polarity::IdleHigh)
                                .master()
                                .master()
                                .lsbfrst()
                                .msbfirst()
                                .ssom()
                                .bit(config.suspend_when_inactive)
                                .ssm()
                                .bit(config.managed_cs == false)
                                .ssoe()
                                .bit(config.managed_cs == true)
                                .mssi()
                                .bits(start_cycle_delay)
                                .midi()
                                .bits(interdata_cycle_delay)
                                .ioswp()
                                .bit(config.swap_miso_mosi == true)
                                .comm()
                                .variant(communication_mode)
                        });

                        // spe: enable the SPI bus
                        spi.cr1.write(|w| w.ssi().slave_not_selected().spe().enabled());
                    } else {
                        // FRXTH: RXNE event is generated if the FIFO level is greater than or equal to
                        //        8-bit
                        // DS: 8-bit data size
                        // SSOE: Slave Select output disabled
                        #[cfg(feature = "f4")]
                        spi.cr2.write(|w| w.ssoe().clear_bit());

                        #[cfg(not(feature = "f4"))]
                        spi.cr2
                            .write(|w| unsafe {
                                w.frxth().set_bit().ds().bits(0b111).ssoe().clear_bit()
                            });

                        let br = Self::compute_baud_rate(clocks.[<apb $apb _timer>](), freq);

                        // CPHA: phase
                        // CPOL: polarity
                        // MSTR: master mode
                        // BR: 1 MHz
                        // SPE: SPI disabled
                        // LSBFIRST: MSB first
                        // SSM: enable software slave management (NSS pin free for other uses)
                        // SSI: set nss high = master mode
                        // CRCEN: hardware CRC calculation disabled
                        // BIDIMODE: 2 line unidirectional (full duplex)
                        spi.cr1.write(|w| unsafe {
                            w.cpha()
                                .bit(mode.phase == Phase::CaptureOnSecondTransition)
                                .cpol()
                                .bit(mode.polarity == Polarity::IdleHigh)
                                .mstr()
                                .set_bit()
                                .br()
                                .bits(br)
                                .spe()
                                .set_bit()
                                .lsbfirst()
                                .clear_bit()
                                .ssi()
                                .set_bit()
                                .ssm()
                                .set_bit()
                                .crcen()
                                .clear_bit()
                                .bidimode()
                                .clear_bit()
                        });
                    }
                }
                Spi { spi }
            }

            #[cfg(not(feature = "h7"))]
            /// Change the baud rate of the SPI
            pub fn reclock<F, C: ClockCfg>(&mut self, freq: u32, clocks: C) {
                self.spi.cr1.modify(|_, w| w.spe().clear_bit());
                self.spi.cr1.modify(|_, w| {
                    unsafe {w.br().bits(Self::compute_baud_rate(clocks.[<apb $apb _timer>](), freq));}
                    w.spe().set_bit()
                });
            }

            fn compute_baud_rate(clocks: u32, freq: u32) -> u8 {
                match clocks / freq {
                    0 => unreachable!(),
                    1..=2 => 0b000,
                    3..=5 => 0b001,
                    6..=11 => 0b010,
                    12..=23 => 0b011,
                    24..=39 => 0b100,
                    40..=95 => 0b101,
                    96..=191 => 0b110,
                    _ => 0b111,
                }
            }}
        }

        impl FullDuplex<u8> for Spi<pac::$SPIX> {
            type Error = Error;

            fn read(&mut self) -> nb::Result<u8, Error> {
                let sr = self.spi.sr.read();

            // todo: DRY between H7 and non-H7 branches here
                cfg_if! {
                    if #[cfg(feature = "h7")] {
                        return Err(if sr.ovr().is_overrun() {
                            nb::Error::Other(Error::Overrun)
                        } else if sr.modf().is_fault() {
                            nb::Error::Other(Error::ModeFault)
                        } else if sr.crce().is_error() {
                            nb::Error::Other(Error::Crc)
                        } else if sr.rxp().is_not_empty() {
                            // NOTE(read_volatile) read only 1 byte (the
                            // svd2rust API only allows reading a
                            // half-word)
                            return Ok(unsafe {
                                ptr::read_volatile(
                                    &self.spi.rxdr as *const _ as *const $TY,
                                )
                            });
                        } else {
                            nb::Error::WouldBlock
                        });
                    } else {
                        return Err(if sr.ovr().bit_is_set() {
                        nb::Error::Other(Error::Overrun)
                    } else if sr.modf().bit_is_set() {
                        nb::Error::Other(Error::ModeFault)
                    } else if sr.crcerr().bit_is_set() {
                        nb::Error::Other(Error::Crc)
                    } else if sr.rxne().bit_is_set() {
                        // NOTE(read_volatile) read only 1 byte (the svd2rust API only allows
                        // reading a half-word)
                        return Ok(unsafe {
                            ptr::read_volatile(&self.spi.dr as *const _ as *const u8)
                        });
                    } else {
                        nb::Error::WouldBlock
                    });
                    }
                }
            }

            fn send(&mut self, byte: u8) -> nb::Result<(), Error> {
                let sr = self.spi.sr.read();

                // todo: DRY between H7 and non-H7 branches here
                cfg_if! {
                    if #[cfg(feature = "h7")] {
                        return  Err(if sr.ovr().is_overrun() {
                            nb::Error::Other(Error::Overrun)
                        } else if sr.modf().is_fault() {
                            nb::Error::Other(Error::ModeFault)
                        } else if sr.crce().is_error() {
                            nb::Error::Other(Error::Crc)
                        } else if sr.txp().is_not_full() {
                            // NOTE(write_volatile) see note above
                            unsafe {
                                ptr::write_volatile(
                                    &self.spi.txdr as *const _ as *mut $TY,
                                    byte,
                                )
                            }
                            // write CSTART to start a transaction in
                            // master mode
                            self.spi.cr1.modify(|_, w| w.cstart().started());

                            return Ok(());
                        } else {
                            nb::Error::WouldBlock
                        });
                    } else {
                        return Err(if sr.ovr().bit_is_set() {
                            nb::Error::Other(Error::Overrun)
                        } else if sr.modf().bit_is_set() {
                            nb::Error::Other(Error::ModeFault)
                        } else if sr.crcerr().bit_is_set() {
                            nb::Error::Other(Error::Crc)
                        } else if sr.txe().bit_is_set() {
                            // NOTE(write_volatile) see note above
                            unsafe { ptr::write_volatile(&self.spi.dr as *const _ as *mut u8, byte) }
                            return Ok(());
                        } else {
                            nb::Error::WouldBlock
                        });
                    }
                }
            }
        }

        impl embedded_hal::blocking::spi::transfer::Default<u8> for Spi<pac::$SPIX> {}

        impl embedded_hal::blocking::spi::write::Default<u8> for Spi<pac::$SPIX> {}
    }
}

#[cfg(not(feature = "f301"))]
hal!(SPI1, spi1, 2);

#[cfg(not(feature = "f3x4"))]
hal!(SPI2, spi2, 1);

// l4x3 and L5 support SPI3, but have an inconsitent naming convention for enabling rcc.
// (ie `sp3en` instead of `spi3en`.)
#[cfg(any(
    feature = "f301",
    feature = "f302",
    feature = "f303",
    feature = "f373",
    feature = "l4x1",
    feature = "l4x4",
    feature = "l4x5",
    feature = "l4x6",
    feature = "g4",
))]
hal!(SPI3, spi3, 1);