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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Serial Peripheral Interface (SPI) bus
use core::ptr;
use core::ops::Deref;

use embedded_hal::spi;
pub use embedded_hal::spi::{Mode, Phase, Polarity};
use nb;

use crate::stm32::{spi1, SPI1, SPI2, SPI3, SPI4, SPI5, SPI6, RCC};

use crate::gpio::{
    gpioa::{PA1, PA5, PA6, PA7, PA9, PA10, PA11, PA12},
    gpiob::{PB0, PB2, PB3, PB4, PB5, PB8, PB10, PB12, PB13, PB14, PB15},
    gpioc::{PC1, PC2, PC3, PC7, PC10, PC11, PC12},
    gpiod::{PD0, PD3, PD6},
    gpioe::{PE2, PE5, PE6, PE12, PE13, PE14},
    gpiof::{PF7, PF8, PF9, PF11},
    gpiog::{PG11, PG12, PG13, PG14},
    gpioh::{PH6, PH7},
    gpioi::{PI1, PI2, PI3},
};

use crate::gpio::{Alternate, AF5, AF6, AF7};

use crate::rcc::Clocks;
use crate::time::Hertz;

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

pub trait Pins<SPI> {}
pub trait PinSck<SPI> {}
pub trait PinMiso<SPI> {}
pub trait PinMosi<SPI> {}

impl<SPI, SCK, MISO, MOSI> Pins<SPI> for (SCK, MISO, MOSI)
where
    SCK: PinSck<SPI>,
    MISO: PinMiso<SPI>,
    MOSI: PinMosi<SPI>,
{}

/// A filler type for when the SCK pin is unnecessary
pub struct NoSck;
/// A filler type for when the Miso pin is unnecessary
pub struct NoMiso;
/// A filler type for when the Mosi pin is unnecessary
pub struct NoMosi;

macro_rules! pins {
    ($($SPIX:ty: SCK: [$($SCK:ty),*] MISO: [$($MISO:ty),*] MOSI: [$($MOSI:ty),*])+) => {
        $(
            $(
                impl PinSck<$SPIX> for $SCK {}
            )*
            $(
                impl PinMiso<$SPIX> for $MISO {}
            )*
            $(
                impl PinMosi<$SPIX> for $MOSI {}
            )*
        )+
    }
}

pins! {
    SPI1:
        SCK: [
            NoSck,
            PA5<Alternate<AF5>>,
            PB3<Alternate<AF5>>
        ]
        MISO: [
            NoMiso,
            PA6<Alternate<AF5>>,
            PB4<Alternate<AF5>>
        ]
        MOSI: [
            NoMosi,
            PA7<Alternate<AF5>>,
            PB5<Alternate<AF5>>
        ]

    SPI2:
        SCK: [
            NoSck,
            PB10<Alternate<AF5>>,
            PB13<Alternate<AF5>>
        ]
        MISO: [
            NoMiso,
            PB14<Alternate<AF5>>,
            PC2<Alternate<AF5>>
        ]
        MOSI: [
            NoMosi,
            PB15<Alternate<AF5>>,
            PC3<Alternate<AF5>>
        ]
}

pins! {
    SPI3:
        SCK: [
            NoSck,
            PB3<Alternate<AF6>>,
            PC10<Alternate<AF6>>
        ]
        MISO: [
            NoMiso,
            PB4<Alternate<AF6>>,
            PC11<Alternate<AF6>>
        ]
        MOSI: [
            NoMosi,
            PB5<Alternate<AF6>>,
            PC12<Alternate<AF6>>
        ]
}

pins! {
    SPI2:
        SCK: [PD3<Alternate<AF5>>]
        MISO: []
        MOSI: []
    SPI3:
        SCK: []
        MISO: []
        MOSI: [PD6<Alternate<AF5>>]
    SPI4:
        SCK: [
            NoSck,
            PE2<Alternate<AF5>>,
            PE12<Alternate<AF5>>
        ]
        MISO: [
            NoMiso,
            PE5<Alternate<AF5>>,
            PE13<Alternate<AF5>>
        ]
        MOSI: [
            NoMosi,
            PE6<Alternate<AF5>>,
            PE14<Alternate<AF5>>
        ]
}

pins! {
    SPI2:
        SCK: [PI1<Alternate<AF5>>]
        MISO: [PI2<Alternate<AF5>>]
        MOSI: [PI3<Alternate<AF5>>]
}

pins! {
    SPI2:
        SCK: [PC7<Alternate<AF5>>]
        MISO: []
        MOSI: []
}

pins! {
    SPI5:
        SCK: [
            NoSck,
            PB0<Alternate<AF6>>
        ]
        MISO: [
            NoMiso,
            PA12<Alternate<AF6>>
        ]
        MOSI: [
            NoMosi,
            PA10<Alternate<AF6>>,
            PB8<Alternate<AF6>>
        ]
}

pins! {
    SPI3:
        SCK: [PB12<Alternate<AF7>>]
        MISO: []
        MOSI: []
    SPI4:
        SCK: [PB13<Alternate<AF6>>]
        MISO: [PA11<Alternate<AF6>>]
        MOSI: [PA1<Alternate<AF5>>]
    SPI5:
        SCK: [
            PE2<Alternate<AF6>>,
            PE12<Alternate<AF6>>
        ]
        MISO: [
            PE5<Alternate<AF6>>,
            PE13<Alternate<AF6>>
        ]
        MOSI: [
            PE6<Alternate<AF6>>,
            PE14<Alternate<AF6>>
        ]
}

pins! {
    SPI2:
        SCK: [PA9<Alternate<AF5>>]
        MISO: [PA12<Alternate<AF5>>]
        MOSI: [PA10<Alternate<AF5>>]
}

pins! {
    SPI5:
        SCK: [
            PF7<Alternate<AF5>>,
            PH6<Alternate<AF5>>
        ]
        MISO: [
            PF8<Alternate<AF5>>,
            PH7<Alternate<AF5>>
        ]
        MOSI: [
            PF9<Alternate<AF5>>,
            PF11<Alternate<AF5>>
        ]

    SPI6:
        SCK: [
            NoSck,
            PG13<Alternate<AF5>>
        ]
        MISO: [
            NoMiso,
            PG12<Alternate<AF5>>
        ]
        MOSI: [
            NoMosi,
            PG14<Alternate<AF5>>
        ]
}

pins! {
    SPI2:
        SCK: []
        MISO: []
        MOSI: [PC1<Alternate<AF7>>]

    SPI3:
        SCK: []
        MISO: []
        MOSI: [
            PB0<Alternate<AF7>>,
            PB2<Alternate<AF7>>,
            PD0<Alternate<AF6>>
        ]

    SPI4:
        SCK: [PG11<Alternate<AF6>>]
        MISO: [
            PG12<Alternate<AF6>>,
            PD0<Alternate<AF5>>
        ]
        MOSI: [PG13<Alternate<AF6>>]
}

pins! {
    SPI2:
        SCK: []
        MISO: []
        MOSI: [PC1<Alternate<AF5>>]
}

/// Interrupt events
pub enum Event {
    /// New data has been received
    Rxne,
    /// Data can be sent
    Txe,
    /// An error occurred
    Error,
}

#[derive(Debug)]
pub struct Spi<SPI, PINS> {
    spi: SPI,
    pins: PINS,
}

impl<PINS> Spi<SPI1, PINS> {
    pub fn spi1(spi: SPI1, pins: PINS, mode: Mode, freq: Hertz, clocks: Clocks) -> Self
    where
        PINS: Pins<SPI1>
    {
        // NOTE(unsafe) This executes only during initialisation
        let rcc = unsafe { &(*RCC::ptr()) };

        // Enable clock for SPI
        rcc.apb2enr.modify(|_, w| w.spi1en().set_bit());

        Spi { spi, pins }.init(mode, freq, clocks.pclk2())
    }
}

impl<PINS> Spi<SPI2, PINS> {
    pub fn spi2(spi: SPI2, pins: PINS, mode: Mode, freq: Hertz, clocks: Clocks) -> Self
    where
        PINS: Pins<SPI2>
    {
        // NOTE(unsafe) This executes only during initialisation
        let rcc = unsafe { &(*RCC::ptr()) };

        // Enable clock for SPI
        rcc.apb1enr.modify(|_, w| w.spi2en().set_bit());

        Spi { spi, pins }.init(mode, freq, clocks.pclk1())
    }
}

impl<PINS> Spi<SPI3, PINS> {
    pub fn spi3(spi: SPI3, pins: PINS, mode: Mode, freq: Hertz, clocks: Clocks) -> Self
    where
        PINS: Pins<SPI3>
    {
        // NOTE(unsafe) This executes only during initialisation
        let rcc = unsafe { &(*RCC::ptr()) };

        // Enable clock for SPI
        rcc.apb1enr.modify(|_, w| w.spi3en().set_bit());

        Spi { spi, pins }.init(mode, freq, clocks.pclk1())
    }
}

impl<PINS> Spi<SPI4, PINS> {
    pub fn spi4(spi: SPI4, pins: PINS, mode: Mode, freq: Hertz, clocks: Clocks) -> Self
    where
        PINS: Pins<SPI4>
    {
        // NOTE(unsafe) This executes only during initialisation
        let rcc = unsafe { &(*RCC::ptr()) };

        // Enable clock for SPI
        rcc.apb2enr.modify(|_, w| w.spi4en().set_bit());

        Spi { spi, pins }.init(mode, freq, clocks.pclk2())
    }
}

impl<PINS> Spi<SPI5, PINS> {
    pub fn spi5(spi: SPI5, pins: PINS, mode: Mode, freq: Hertz, clocks: Clocks) -> Self
    where
        PINS: Pins<SPI5>
    {
        // NOTE(unsafe) This executes only during initialisation
        let rcc = unsafe { &(*RCC::ptr()) };

        // Enable clock for SPI
        rcc.apb2enr.modify(|_, w| w.spi5en().set_bit());

        Spi { spi, pins }.init(mode, freq, clocks.pclk2())
    }
}

impl<PINS> Spi<SPI6, PINS> {
    pub fn spi6(spi: SPI6, pins: PINS, mode: Mode, freq: Hertz, clocks: Clocks) -> Self
    where
        PINS: Pins<SPI6>
    {
        // NOTE(unsafe) This executes only during initialisation
        let rcc = unsafe { &(*RCC::ptr()) };

        // Enable clock for SPI
        rcc.apb2enr.modify(|_, w| w.spi6en().set_bit());

        Spi { spi, pins }.init(mode, freq, clocks.pclk2())
    }
}

impl<SPI, PINS> Spi<SPI, PINS>
where
    SPI: Deref<Target = spi1::RegisterBlock>,
{
    pub fn init(self, mode: Mode, freq: Hertz, clock: Hertz) -> Self
    {
        // disable SS output
        self.spi.cr2.write(|w| w.ssoe().clear_bit());

        let br = match clock.0 / freq.0 {
            0 => unreachable!(),
            1...2 => 0b000,
            3...5 => 0b001,
            6...11 => 0b010,
            12...23 => 0b011,
            24...47 => 0b100,
            48...95 => 0b101,
            96...191 => 0b110,
            _ => 0b111,
        };

        // mstr: master configuration
        // lsbfirst: MSB first
        // ssm: enable software slave management (NSS pin free for other uses)
        // ssi: set nss high = master mode
        // bidimode: 2-line unidirectional
        // spe: enable the SPI bus
        self.spi.cr1.write(|w| { w
            .cpha()
            .bit(mode.phase == Phase::CaptureOnSecondTransition)
            .cpol()
            .bit(mode.polarity == Polarity::IdleHigh)
            .mstr()
            .set_bit()
            .br()
            .bits(br)
            .lsbfirst()
            .clear_bit()
            .ssm()
            .set_bit()
            .ssi()
            .set_bit()
            .rxonly()
            .clear_bit()
            .bidimode()
            .clear_bit()
            .spe()
            .set_bit()
        });

        self
    }

    /// Enable interrupts for the given `event`:
    ///  - Received data ready to be read (RXNE)
    ///  - Transmit data register empty (TXE)
    ///  - Transfer error
    pub fn listen(&mut self, event: Event) {
        match event {
            Event::Rxne  => self.spi.cr2.modify(|_, w| { w.rxneie().set_bit() }),
            Event::Txe   => self.spi.cr2.modify(|_, w| { w.txeie().set_bit() }),
            Event::Error => self.spi.cr2.modify(|_, w| { w.errie().set_bit() }),
        }
    }

    /// Disable interrupts for the given `event`:
    ///  - Received data ready to be read (RXNE)
    ///  - Transmit data register empty (TXE)
    ///  - Transfer error
    pub fn unlisten(&mut self, event: Event) {
        match event {
            Event::Rxne  => self.spi.cr2.modify(|_, w| { w.rxneie().clear_bit() }),
            Event::Txe   => self.spi.cr2.modify(|_, w| { w.txeie().clear_bit() }),
            Event::Error => self.spi.cr2.modify(|_, w| { w.errie().clear_bit() }),
        }
    }

    /// Return `true` if the TXE flag is set, i.e. new data to transmit
    /// can be written to the SPI.
    pub fn is_txe(&self) -> bool {
        self.spi.sr.read().txe().bit_is_set()
    }

    /// Return `true` if the RXNE flag is set, i.e. new data has been received
    /// and can be read from the SPI.
    pub fn is_rxne(&self) -> bool {
        self.spi.sr.read().rxne().bit_is_set()
    }

    /// Return `true` if the MODF flag is set, i.e. the SPI has experienced a
    /// Master Mode Fault. (see chapter 28.3.10 of the STM32F4 Reference Manual)
    pub fn is_modf(&self) -> bool {
        self.spi.sr.read().modf().bit_is_set()
    }

    /// Return `true` if the OVR flag is set, i.e. new data has been received
    /// while the receive data register was already filled.
    pub fn is_ovr(&self) -> bool {
        self.spi.sr.read().ovr().bit_is_set()
    }

    pub fn free(self) -> (SPI, PINS) {
        (self.spi, self.pins)
    }
}

impl<SPI, PINS> spi::FullDuplex<u8> for Spi<SPI, PINS>
where
    SPI: Deref<Target = spi1::RegisterBlock>,
{
    type Error = Error;

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

        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();

        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<SPI, PINS> embedded_hal::blocking::spi::transfer::Default<u8> for Spi<SPI, PINS>
where
    SPI: Deref<Target = spi1::RegisterBlock>,
{}

impl<SPI, PINS> embedded_hal::blocking::spi::write::Default<u8> for Spi<SPI, PINS>
where
    SPI: Deref<Target = spi1::RegisterBlock>,
{}