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
use core::fmt;
use core::marker::PhantomData;
use core::ops::Deref;
use core::ops::DerefMut;
use core::pin::Pin;
use core::ptr;

use as_slice::{AsMutSlice, AsSlice};

use crate::dma;
use crate::embedded_time::rate::Extensions as _;
use crate::hal::prelude::*;
use crate::hal::serial;
use crate::pac;
use crate::state;
use nb::block;

#[cfg(any(feature = "device-selected",))]
use crate::pac::{RCC, UART4, UART5, UART7, USART1, USART2, USART3, USART6};

#[cfg(any(feature = "device-selected",))]
use crate::gpio::{
    gpioa::{PA0, PA1, PA10, PA2, PA3, PA9},
    gpiob::{PB10, PB11, PB6, PB7},
    gpioc::{PC10, PC11, PC12, PC6, PC7},
    gpiod::{PD2, PD5, PD6, PD8, PD9},
    gpioe::{PE7, PE8},
    gpiof::{PF6, PF7},
    gpiog::{PG14, PG9},
    Alternate, AF7, AF8,
};

use crate::embedded_time::rate::BytesPerSecond;
use crate::rcc::Clocks;

/// Serial error
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// Framing error
    Framing,
    /// Noise error
    Noise,
    /// RX buffer overrun
    Overrun,
    /// Parity check error
    Parity,
}

pub trait Pins<USART> {}
pub trait PinTx<USART> {}
pub trait PinRx<USART> {}

impl<USART, TX, RX> Pins<USART> for (TX, RX)
where
    TX: PinTx<USART>,
    RX: PinRx<USART>,
{
}

mod f7xx_pins {
    //table 13 in stm32f765bg.pdf
    use super::{PinRx, PinTx};
    use crate::gpio::{
        gpioa::{PA11, PA12, PA15, PA8},
        gpiob::{PB12, PB13, PB14, PB15, PB3, PB4, PB5, PB6, PB8, PB9},
        gpiod::{PD0, PD1},
        gpioh::{PH13, PH14},
        gpioi::PI9,
        Alternate, AF1, AF12, AF4, AF6, AF7, AF8,
    };
    use crate::pac::{UART4, UART5, UART7, USART1};
    impl PinTx<USART1> for PB14<Alternate<AF4>> {}
    impl PinRx<USART1> for PB15<Alternate<AF4>> {}

    impl PinTx<UART4> for PA11<Alternate<AF6>> {}
    impl PinRx<UART4> for PA12<Alternate<AF6>> {}

    impl PinTx<UART4> for PD1<Alternate<AF8>> {}
    impl PinRx<UART4> for PD0<Alternate<AF8>> {}

    impl PinTx<UART4> for PH13<Alternate<AF8>> {}
    impl PinRx<UART4> for PH14<Alternate<AF8>> {}

    impl PinRx<UART4> for PI9<Alternate<AF8>> {}

    impl PinTx<UART5> for PB6<Alternate<AF1>> {}
    impl PinRx<UART5> for PB5<Alternate<AF1>> {}

    impl PinTx<UART5> for PB9<Alternate<AF7>> {}
    impl PinRx<UART5> for PB8<Alternate<AF7>> {}

    impl PinTx<UART5> for PB13<Alternate<AF8>> {}
    impl PinRx<UART5> for PB12<Alternate<AF8>> {}

    impl PinTx<UART7> for PA15<Alternate<AF12>> {}
    impl PinRx<UART7> for PA8<Alternate<AF12>> {}

    impl PinTx<UART7> for PB4<Alternate<AF12>> {}
    impl PinRx<UART7> for PB3<Alternate<AF12>> {}
}

#[cfg(any(
    feature = "stm32f765",
    feature = "stm32f767",
    feature = "stm32f768",
    feature = "stm32f769"
))]
pub use f7xx_pins::*;

impl PinTx<USART1> for PA9<Alternate<AF7>> {}
impl PinTx<USART1> for PB6<Alternate<AF7>> {}
impl PinTx<USART2> for PA2<Alternate<AF7>> {}
impl PinTx<USART2> for PD5<Alternate<AF7>> {}
impl PinTx<USART3> for PB10<Alternate<AF7>> {}
impl PinTx<USART3> for PC10<Alternate<AF7>> {}
impl PinTx<USART3> for PD8<Alternate<AF7>> {}
impl PinTx<UART4> for PA0<Alternate<AF8>> {}
impl PinTx<UART4> for PC10<Alternate<AF8>> {}
impl PinTx<UART5> for PC12<Alternate<AF8>> {}
impl PinTx<USART6> for PC6<Alternate<AF8>> {}
impl PinTx<USART6> for PG14<Alternate<AF8>> {}
impl PinTx<UART7> for PE8<Alternate<AF8>> {}
impl PinTx<UART7> for PF7<Alternate<AF8>> {}

impl PinRx<USART1> for PA10<Alternate<AF7>> {}
impl PinRx<USART1> for PB7<Alternate<AF7>> {}
impl PinRx<USART2> for PA3<Alternate<AF7>> {}
impl PinRx<USART2> for PD6<Alternate<AF7>> {}
impl PinRx<USART3> for PB11<Alternate<AF7>> {}
impl PinRx<USART3> for PC11<Alternate<AF7>> {}
impl PinRx<USART3> for PD9<Alternate<AF7>> {}
impl PinRx<UART4> for PA1<Alternate<AF8>> {}
impl PinRx<UART4> for PC11<Alternate<AF8>> {}
impl PinRx<UART5> for PD2<Alternate<AF8>> {}
impl PinRx<USART6> for PC7<Alternate<AF8>> {}
impl PinRx<USART6> for PG9<Alternate<AF8>> {}
impl PinRx<UART7> for PE7<Alternate<AF8>> {}
impl PinRx<UART7> for PF6<Alternate<AF8>> {}

/// Serial abstraction
pub struct Serial<USART, PINS> {
    usart: USART,
    pins: PINS,
}

impl<USART, PINS> Serial<USART, PINS>
where
    PINS: Pins<USART>,
    USART: Instance,
{
    pub fn new(usart: USART, pins: PINS, clocks: Clocks, config: Config) -> Self {
        // NOTE(unsafe) This executes only during initialisation
        let rcc = unsafe { &(*RCC::ptr()) };

        // TODO: The unsafe calls below should be replaced with accessing
        //       the correct registers directly.

        USART::select_sysclock(rcc);
        USART::enable_clock(rcc);

        // Calculate correct baudrate divisor on the fly
        let brr = match config.oversampling {
            Oversampling::By8 => {
                usart.cr1.modify(|_, w| w.over8().set_bit());

                let usart_div = 2 * clocks.sysclk().0 / config.baud_rate.0;

                0xfff0 & usart_div | 0x0007 & ((usart_div & 0x000f) >> 1)
            }
            Oversampling::By16 => {
                usart.cr1.modify(|_, w| w.over8().clear_bit());

                clocks.sysclk().0 / config.baud_rate.0
            }
        };

        usart.brr.write(|w| unsafe { w.bits(brr) });

        // Set character match and reset other registers to disable advanced USART features
        let ch = config.character_match.unwrap_or(0);
        usart.cr2.write(|w| w.add().bits(ch));

        // Enable transmission and receiving
        usart
            .cr1
            .modify(|_, w| w.te().enabled().re().enabled().ue().enabled());

        // Enable DMA
        usart.cr3.write(|w| w.dmat().enabled().dmar().enabled());

        Serial { usart, pins }
    }

    /// Starts listening for an interrupt event
    pub fn listen(&mut self, event: Event) {
        match event {
            Event::Rxne => self.usart.cr1.modify(|_, w| w.rxneie().set_bit()),
            Event::Txe => self.usart.cr1.modify(|_, w| w.txeie().set_bit()),
            Event::CharacterMatch => self.usart.cr1.modify(|_, w| w.cmie().set_bit()),
            Event::Error => self.usart.cr3.modify(|_, w| w.eie().set_bit()),
        }
    }

    /// End listening for an interrupt event
    pub fn unlisten(&mut self, event: Event) {
        match event {
            Event::Rxne => self.usart.cr1.modify(|_, w| w.rxneie().clear_bit()),
            Event::Txe => self.usart.cr1.modify(|_, w| w.txeie().clear_bit()),
            Event::CharacterMatch => self.usart.cr1.modify(|_, w| w.cmie().clear_bit()),
            Event::Error => self.usart.cr3.modify(|_, w| w.eie().clear_bit()),
        }
    }

    pub fn split(self) -> (Tx<USART>, Rx<USART>) {
        (
            Tx {
                _usart: PhantomData,
            },
            Rx {
                _usart: PhantomData,
            },
        )
    }

    pub fn release(self) -> (USART, PINS) {
        (self.usart, self.pins)
    }
}

impl<USART, PINS> serial::Read<u8> for Serial<USART, PINS>
where
    USART: Instance,
{
    type Error = Error;

    fn read(&mut self) -> nb::Result<u8, Error> {
        let mut rx: Rx<USART> = Rx {
            _usart: PhantomData,
        };
        rx.read()
    }
}

impl<USART, PINS> serial::Write<u8> for Serial<USART, PINS>
where
    USART: Instance,
{
    type Error = Error;

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        let mut tx: Tx<USART> = Tx {
            _usart: PhantomData,
        };
        tx.flush()
    }

    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        let mut tx: Tx<USART> = Tx {
            _usart: PhantomData,
        };
        tx.write(byte)
    }
}

/// Serial receiver
pub struct Rx<USART> {
    _usart: PhantomData<USART>,
}

impl<USART> Rx<USART>
where
    USART: Instance,
    Self: dma::Target,
{
    /// Reads data using DMA until `buffer` is full
    ///
    /// DMA supports transfers up to 65535 bytes. If `buffer` is longer, this
    /// method will panic.
    pub fn read_all<B>(
        self,
        buffer: Pin<B>,
        dma: &dma::Handle<<Self as dma::Target>::Instance, state::Enabled>,
        stream: <Self as dma::Target>::Stream,
    ) -> dma::Transfer<Self, B, dma::Ready>
    where
        B: DerefMut + 'static,
        B::Target: AsMutSlice<Element = u8>,
    {
        // This is safe, as we're only using the USART instance to access the
        // address of one register.
        let address = &unsafe { &*USART::ptr() }.rdr as *const _ as _;

        // Safe, because the trait bounds on this method guarantee that `buffer`
        // can be written to safely.
        unsafe {
            dma::Transfer::new(
                dma,
                stream,
                buffer,
                self,
                address,
                dma::Direction::PeripheralToMemory,
            )
        }
    }
}

impl<USART> serial::Read<u8> for Rx<USART>
where
    USART: Instance,
{
    type Error = Error;

    fn read(&mut self) -> nb::Result<u8, Error> {
        // NOTE(unsafe) atomic read with no side effects
        let isr = unsafe { (*USART::ptr()).isr.read() };

        // NOTE(unsafe): Only used for atomic writes, to clear error flags.
        let icr = unsafe { &(*USART::ptr()).icr };

        if isr.pe().bit_is_set() {
            icr.write(|w| w.pecf().clear());
            return Err(nb::Error::Other(Error::Parity));
        }
        if isr.fe().bit_is_set() {
            icr.write(|w| w.fecf().clear());
            return Err(nb::Error::Other(Error::Framing));
        }
        if isr.nf().bit_is_set() {
            icr.write(|w| w.ncf().clear());
            return Err(nb::Error::Other(Error::Noise));
        }
        if isr.ore().bit_is_set() {
            icr.write(|w| w.orecf().clear());
            return Err(nb::Error::Other(Error::Overrun));
        }

        if isr.rxne().bit_is_set() {
            // NOTE(unsafe): Atomic read with no side effects
            return Ok(unsafe {
                // Casting to `u8` should be fine, as we've configured the USART
                // to use 8 data bits.
                (*USART::ptr()).rdr.read().rdr().bits() as u8
            });
        }

        Err(nb::Error::WouldBlock)
    }
}

/// Serial transmitter
pub struct Tx<USART> {
    _usart: PhantomData<USART>,
}

impl<USART> Tx<USART>
where
    Self: dma::Target,
    USART: Instance,
{
    /// Writes data using DMA
    ///
    /// DMA supports transfers up to 65535 bytes. If `data` is longer, this
    /// method will panic.
    pub fn write_all<B>(
        self,
        data: Pin<B>,
        dma: &dma::Handle<<Self as dma::Target>::Instance, state::Enabled>,
        stream: <Self as dma::Target>::Stream,
    ) -> dma::Transfer<Self, B, dma::Ready>
    where
        B: Deref + 'static,
        B::Target: AsSlice<Element = u8>,
    {
        // Prepare USART for DMA. See reference manual for STM32F75xxx and
        // STM32F74xxx, section 31.5.15.
        //
        // This is safe, as we're doing just one atomic write.
        let usart = unsafe { &*USART::ptr() };
        usart.icr.write(|w| w.tccf().clear());

        // Safe, because the trait bounds on this method guarantee that `buffer`
        // can be read from safely.
        unsafe {
            dma::Transfer::new(
                dma,
                stream,
                data,
                self,
                &usart.tdr as *const _ as _,
                dma::Direction::MemoryToPeripheral,
            )
        }
    }
}

impl<USART> serial::Write<u8> for Tx<USART>
where
    USART: Instance,
{
    type Error = Error;

    fn flush(&mut self) -> nb::Result<(), Self::Error> {
        // NOTE(unsafe) atomic read with no side effects
        let isr = unsafe { (*USART::ptr()).isr.read() };

        if isr.tc().bit_is_set() {
            Ok(())
        } else {
            Err(nb::Error::WouldBlock)
        }
    }

    fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
        // NOTE(unsafe) atomic read with no side effects
        let isr = unsafe { (*USART::ptr()).isr.read() };

        if isr.txe().bit_is_set() {
            // NOTE(unsafe) atomic write to stateless register
            // NOTE(write_volatile) 8-bit write that's not possible through the svd2rust API
            unsafe { ptr::write_volatile(&(*USART::ptr()).tdr as *const _ as *mut _, byte) }
            Ok(())
        } else {
            Err(nb::Error::WouldBlock)
        }
    }
}

/// USART configuration
pub struct Config {
    pub baud_rate: BytesPerSecond,
    pub oversampling: Oversampling,
    pub character_match: Option<u8>,
}

pub enum Oversampling {
    By8,
    By16,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            baud_rate: 115_200.Bps(),
            oversampling: Oversampling::By16,
            character_match: None,
        }
    }
}

/// Interrupt event
#[derive(Debug)]
pub enum Event {
    /// New data has been received
    Rxne,
    /// New data can be sent
    Txe,
    /// Character match interrupt
    CharacterMatch,
    /// Error interrupt
    Error,
}

/// Implemented by all USART instances
pub trait Instance: Deref<Target = pac::usart1::RegisterBlock> {
    fn ptr() -> *const pac::usart1::RegisterBlock;
    fn select_sysclock(rcc: &pac::rcc::RegisterBlock);
    fn enable_clock(rcc: &pac::rcc::RegisterBlock);
}

macro_rules! impl_instance {
    ($(
        $USARTX:ident: ($apbXenr:ident, $usartXsel:ident, $usartXen:ident),
    )+) => {
        $(
            impl Instance for $USARTX {
                fn ptr() -> *const pac::usart1::RegisterBlock {
                    $USARTX::ptr()
                }

                fn select_sysclock(rcc: &pac::rcc::RegisterBlock) {
                    rcc.dckcfgr2.modify(|_, w| w.$usartXsel().bits(1));
                }

                fn enable_clock(rcc: &pac::rcc::RegisterBlock) {
                    rcc.$apbXenr.modify(|_, w| w.$usartXen().set_bit());
                }
            }
        )+
    }
}

#[cfg(any(feature = "device-selected",))]
impl_instance! {
    USART1: (apb2enr, usart1sel, usart1en),
    USART2: (apb1enr, usart2sel, usart2en),
    USART3: (apb1enr, usart3sel, usart3en),
    UART4:  (apb1enr, uart4sel,  uart4en),
    UART5:  (apb1enr, uart5sel,  uart5en),
    USART6: (apb2enr, usart6sel, usart6en),
    UART7:  (apb1enr, uart7sel,  uart7en),
}

impl<USART> fmt::Write for Tx<USART>
where
    Tx<USART>: serial::Write<u8>,
{
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let _ = s.as_bytes().iter().map(|c| block!(self.write(*c))).last();
        Ok(())
    }
}