-
Notifications
You must be signed in to change notification settings - Fork 105
/
serial.rs
1316 lines (1180 loc) · 44.1 KB
/
serial.rs
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Serial
//!
//! # Examples
//!
//! - [Simple Blocking Example](https://github.com/stm32-rs/stm32h7xx-hal/blob/master/examples/serial.rs)
//! - [Serial Transfer using DMA](https://github.com/stm32-rs/stm32h7xx-hal/blob/master/examples/serial-dma.rs)
//! - [Advanced USART Functions](https://github.com/stm32-rs/stm32h7xx-hal/blob/master/examples/serial-advanced.rs)
//! - [Inverted Signal Levels](https://github.com/stm32-rs/stm32h7xx-hal/blob/master/examples/serial-inverted-loopback.rs)
use core::cell::UnsafeCell;
use core::fmt;
use core::marker::PhantomData;
use core::ptr;
use embedded_hal::blocking::serial as serial_block;
use embedded_hal::prelude::*;
use embedded_hal::serial;
use nb::block;
use stm32::usart1::cr2::{
CLKEN_A, CPHA_A, CPOL_A, LBCL_A, MSBFIRST_A, RXINV_A, TXINV_A,
};
use stm32::usart1::cr3::HDSEL_A;
use crate::gpio::{self, Alternate};
use crate::rcc::{rec, CoreClocks, ResetEnable};
use crate::stm32;
#[cfg(feature = "rm0455")]
use crate::stm32::rcc::cdccip2r::{USART16910SEL_A, USART234578SEL_A};
#[cfg(feature = "rm0468")]
use crate::stm32::rcc::d2ccip2r::{USART16910SEL_A, USART234578SEL_A};
#[cfg(any(feature = "rm0433", feature = "rm0399"))]
use crate::stm32::rcc::d2ccip2r::{USART16SEL_A, USART234578SEL_A};
use crate::stm32::usart1::cr1::{M0_A as M0, PCE_A as PCE, PS_A as PS};
use crate::stm32::{UART4, UART5, UART7, UART8};
#[cfg(any(feature = "rm0455", feature = "rm0468"))]
use crate::stm32::{UART9, USART10};
use crate::stm32::{USART1, USART2, USART3, USART6};
use crate::time::Hertz;
/// Serial error
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Error {
/// Framing error
Framing,
/// Noise error
Noise,
/// RX buffer overrun
Overrun,
/// Parity check error
Parity,
}
/// Interrupt event
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Event {
/// New data has been received
Rxne,
/// New data can be sent
Txe,
/// Idle line state detected
Idle,
///Tx threshlold interrupt enable
Txftie,
///Rx threshlold interrupt enable
Rxftie,
}
pub mod config {
use crate::time::Hertz;
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum FifoThreshold {
Eighth,
Quarter,
Half,
ThreeQuarter,
SevenEighth,
Full,
}
/// The parity bits appended to each serial data word
///
/// When enabled parity bits will be automatically added by hardware on transmit, and automatically checked by
/// hardware on receive. For example, `read()` would return [`Error::Parity`](super::Error::Parity).
///
/// Note that parity bits are included in the serial word length, so if parity is used word length will be set to 9.
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Parity {
ParityNone,
ParityEven,
ParityOdd,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum StopBits {
#[doc = "1 stop bit"]
Stop1,
#[doc = "0.5 stop bits"]
Stop0p5,
#[doc = "2 stop bits"]
Stop2,
#[doc = "1.5 stop bits"]
Stop1p5,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum BitOrder {
LsbFirst,
MsbFirst,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum ClockPhase {
First,
Second,
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum ClockPolarity {
IdleHigh,
IdleLow,
}
/// A structure for specifying the USART or UART configuration. Fields
/// relating to synchronous mode are ignored for UART peripherals.
///
/// This structure uses builder semantics to generate the configuration.
///
/// ```
/// let config = Config::new().partity_odd();
/// ```
#[derive(Copy, Clone)]
pub struct Config {
pub baudrate: Hertz,
pub parity: Parity,
pub stopbits: StopBits,
pub bitorder: BitOrder,
pub clockphase: ClockPhase,
pub clockpolarity: ClockPolarity,
pub lastbitclockpulse: bool,
pub swaptxrx: bool,
pub invertrx: bool,
pub inverttx: bool,
pub rxfifothreshold: FifoThreshold,
pub txfifothreshold: FifoThreshold,
pub halfduplex: bool,
}
impl Config {
/// Create a default configuration for the USART or UART interface
///
/// * 8 bits, 1 stop bit, no parity (8N1)
/// * LSB first
pub fn new(frequency: Hertz) -> Self {
Config {
baudrate: frequency,
parity: Parity::ParityNone,
stopbits: StopBits::Stop1,
bitorder: BitOrder::LsbFirst,
clockphase: ClockPhase::First,
clockpolarity: ClockPolarity::IdleLow,
lastbitclockpulse: false,
swaptxrx: false,
invertrx: false,
inverttx: false,
rxfifothreshold: FifoThreshold::Eighth,
txfifothreshold: FifoThreshold::Eighth,
halfduplex: false,
}
}
pub fn baudrate(mut self, baudrate: Hertz) -> Self {
self.baudrate = baudrate;
self
}
pub fn parity_none(mut self) -> Self {
self.parity = Parity::ParityNone;
self
}
/// Enables Even Parity
///
/// Note that parity bits are included in the serial word length, so if parity is used word length will be set
/// to 9.
pub fn parity_even(mut self) -> Self {
self.parity = Parity::ParityEven;
self
}
/// Enables Odd Parity
///
/// Note that parity bits are included in the serial word length, so if parity is used word length will be set
/// to 9.
pub fn parity_odd(mut self) -> Self {
self.parity = Parity::ParityOdd;
self
}
/// Specify the number of stop bits
pub fn stopbits(mut self, stopbits: StopBits) -> Self {
self.stopbits = stopbits;
self
}
/// Specify the bit order
pub fn bitorder(mut self, bitorder: BitOrder) -> Self {
self.bitorder = bitorder;
self
}
/// Specify the clock phase. Only applies to USART peripherals
pub fn clockphase(mut self, clockphase: ClockPhase) -> Self {
self.clockphase = clockphase;
self
}
/// Specify the clock polarity. Only applies to USART peripherals
pub fn clockpolarity(mut self, clockpolarity: ClockPolarity) -> Self {
self.clockpolarity = clockpolarity;
self
}
/// Specify if the last bit transmitted in each word has a corresponding
/// clock pulse in the SCLK pin. Only applies to USART peripherals
pub fn lastbitclockpulse(mut self, lastbitclockpulse: bool) -> Self {
self.lastbitclockpulse = lastbitclockpulse;
self
}
/// If `true`, swap the Tx and Rx pins
pub fn swaptxrx(mut self, swaptxrx: bool) -> Self {
self.swaptxrx = swaptxrx;
self
}
/// If `true`, RX pin signal levels are inverted
pub fn invertrx(mut self, invertrx: bool) -> Self {
self.invertrx = invertrx;
self
}
/// If `true`, TX pin signal levels are inverted
pub fn inverttx(mut self, inverttx: bool) -> Self {
self.inverttx = inverttx;
self
}
pub fn rxfifothreshold(
mut self,
rxfifothreshold: FifoThreshold,
) -> Self {
self.rxfifothreshold = rxfifothreshold;
self
}
pub fn txfifothreshold(
mut self,
txfifothreshold: FifoThreshold,
) -> Self {
self.txfifothreshold = txfifothreshold;
self
}
/// If `true`, sets to half-duplex mode
pub fn halfduplex(mut self, halfduplex: bool) -> Self {
self.halfduplex = halfduplex;
self
}
}
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct InvalidConfig;
impl Default for Config {
fn default() -> Config {
Self::new(Hertz::from_raw(19_200)) // 19k2 baud
}
}
impl From<Hertz> for Config {
fn from(frequency: Hertz) -> Config {
Self::new(frequency)
}
}
}
pub trait Pins<USART> {
const SYNCHRONOUS: bool = false;
}
pub trait PinTx<USART> {}
pub trait PinRx<USART> {}
pub trait PinCk<USART> {}
impl<USART, TX, RX> Pins<USART> for (TX, RX)
where
TX: PinTx<USART>,
RX: PinRx<USART>,
{
}
impl<USART, TX, RX, CK> Pins<USART> for (TX, RX, CK)
where
TX: PinTx<USART>,
RX: PinRx<USART>,
CK: PinCk<USART>,
{
const SYNCHRONOUS: bool = true;
}
/// A filler type for when the Tx pin is unnecessary
pub struct NoTx;
/// A filler type for when the Rx pin is unnecessary
pub struct NoRx;
/// A filler type for when the Ck pin is unnecessary
pub struct NoCk;
macro_rules! usart_pins {
($($USARTX:ty: TX: [$($TX:ty),*] RX: [$($RX:ty),*] CK: [$($CK:ty),*])+) => {
$(
$(
impl PinTx<$USARTX> for $TX {}
)*
$(
impl PinRx<$USARTX> for $RX {}
)*
$(
impl PinCk<$USARTX> for $CK {}
)*
)+
}
}
macro_rules! uart_pins {
($($UARTX:ty:
TX: [$($( #[ $pmeta1:meta ] )* $TX:ty),*]
RX: [$($( #[ $pmeta2:meta ] )* $RX:ty),*]
)+) => {
$(
$(
$( #[ $pmeta1 ] )*
impl PinTx<$UARTX> for $TX {}
)*
$(
$( #[ $pmeta2 ] )*
impl PinRx<$UARTX> for $RX {}
)*
)+
}
}
usart_pins! {
USART1:
TX: [
NoTx,
gpio::PA9<Alternate<7>>,
gpio::PB6<Alternate<7>>,
gpio::PB14<Alternate<4>>
]
RX: [
NoRx,
gpio::PA10<Alternate<7>>,
gpio::PB7<Alternate<7>>,
gpio::PB15<Alternate<4>>
]
CK: [
NoCk,
gpio::PA8<Alternate<7>>
]
USART2:
TX: [
NoTx,
gpio::PA2<Alternate<7>>,
gpio::PD5<Alternate<7>>
]
RX: [
NoRx,
gpio::PA3<Alternate<7>>,
gpio::PD6<Alternate<7>>
]
CK: [
NoCk,
gpio::PA4<Alternate<7>>,
gpio::PD7<Alternate<7>>
]
USART3:
TX: [
NoTx,
gpio::PB10<Alternate<7>>,
gpio::PC10<Alternate<7>>,
gpio::PD8<Alternate<7>>
]
RX: [
NoRx,
gpio::PB11<Alternate<7>>,
gpio::PC11<Alternate<7>>,
gpio::PD9<Alternate<7>>
]
CK: [
NoCk,
gpio::PB12<Alternate<7>>,
gpio::PC12<Alternate<7>>,
gpio::PD10<Alternate<7>>
]
USART6:
TX: [
NoTx,
gpio::PC6<Alternate<7>>,
gpio::PG14<Alternate<7>>
]
RX: [
NoRx,
gpio::PC7<Alternate<7>>,
gpio::PG9<Alternate<7>>
]
CK: [
NoCk,
gpio::PC8<Alternate<7>>,
gpio::PG7<Alternate<7>>
]
}
#[cfg(any(feature = "rm0455", feature = "rm0468"))]
usart_pins! {
USART10:
TX: [
NoTx,
gpio::PE3<Alternate<11>>,
gpio::PG12<Alternate<4>>
]
RX: [
NoRx,
gpio::PE2<Alternate<4>>,
gpio::PG11<Alternate<4>>
]
CK: [
NoCk,
gpio::PE15<Alternate<11>>,
gpio::PG15<Alternate<11>>
]
}
uart_pins! {
UART4:
TX: [
NoTx,
gpio::PA0<Alternate<8>>,
gpio::PA12<Alternate<6>>,
gpio::PB9<Alternate<8>>,
gpio::PC10<Alternate<8>>,
gpio::PD1<Alternate<8>>,
gpio::PH13<Alternate<8>>
]
RX: [
NoRx,
gpio::PA1<Alternate<8>>,
gpio::PA11<Alternate<6>>,
gpio::PB8<Alternate<8>>,
gpio::PC11<Alternate<8>>,
gpio::PD0<Alternate<8>>,
gpio::PH14<Alternate<8>>,
#[cfg(not(feature = "rm0468"))]
gpio::PI9<Alternate<8>>
]
UART5:
TX: [
NoTx,
gpio::PB6<Alternate<14>>,
gpio::PB13<Alternate<14>>,
gpio::PC12<Alternate<8>>
]
RX: [
NoRx,
gpio::PB5<Alternate<14>>,
gpio::PB12<Alternate<14>>,
gpio::PD2<Alternate<8>>
]
UART7:
TX: [
NoTx,
gpio::PA15<Alternate<11>>,
gpio::PB4<Alternate<11>>,
gpio::PE8<Alternate<7>>,
gpio::PF7<Alternate<7>>
]
RX: [
NoRx,
gpio::PA8<Alternate<11>>,
gpio::PB3<Alternate<11>>,
gpio::PE7<Alternate<7>>,
gpio::PF6<Alternate<7>>
]
UART8:
TX: [
NoTx,
gpio::PE1<Alternate<8>>,
#[cfg(not(feature = "stm32h7b0"))]
gpio::PJ8<Alternate<8>>
]
RX: [
NoRx,
gpio::PE0<Alternate<8>>,
#[cfg(not(feature = "stm32h7b0"))]
gpio::PJ9<Alternate<8>>
]
}
#[cfg(any(feature = "rm0455", feature = "rm0468"))]
uart_pins! {
UART9:
TX: [
NoTx,
gpio::PD15<Alternate<11>>,
gpio::PG1<Alternate<11>>
]
RX: [
NoRx,
gpio::PD14<Alternate<11>>,
gpio::PG0<Alternate<11>>
]
}
/// Serial abstraction
pub struct Serial<USART> {
pub(crate) usart: USART,
ker_ck: Hertz,
}
/// Serial receiver
pub struct Rx<USART> {
_usart: PhantomData<USART>,
ker_ck: Hertz,
}
/// Serial transmitter
pub struct Tx<USART> {
_usart: PhantomData<USART>,
}
pub trait SerialExt<USART>: Sized {
type Rec: ResetEnable;
fn serial<P: Pins<USART>>(
self,
_pins: P,
config: impl Into<config::Config>,
prec: Self::Rec,
clocks: &CoreClocks,
) -> Result<Serial<USART>, config::InvalidConfig>;
fn serial_unchecked(
self,
config: impl Into<config::Config>,
prec: Self::Rec,
clocks: &CoreClocks,
synchronous: bool,
) -> Result<Serial<USART>, config::InvalidConfig>;
#[deprecated(since = "0.7.0", note = "Deprecated in favour of .serial(..)")]
fn usart(
self,
pins: impl Pins<USART>,
config: impl Into<config::Config>,
prec: Self::Rec,
clocks: &CoreClocks,
) -> Result<Serial<USART>, config::InvalidConfig> {
self.serial(pins, config, prec, clocks)
}
#[deprecated(
since = "0.7.0",
note = "Deprecated in favour of .serial_unchecked(..)"
)]
fn usart_unchecked(
self,
config: impl Into<config::Config>,
prec: Self::Rec,
clocks: &CoreClocks,
synchronous: bool,
) -> Result<Serial<USART>, config::InvalidConfig> {
self.serial_unchecked(config, prec, clocks, synchronous)
}
}
macro_rules! replace_expr {
($_t:tt $sub:expr) => {
$sub
};
}
macro_rules! usart {
($(
$USARTX:ident: ($usartX:ident, $Rec:ident, $pclkX:ident $(, $synchronous:ident)?),
)+) => {
$(
/// Configures a USART peripheral to provide serial
/// communication
impl Serial<$USARTX> {
pub fn $usartX(
usart: $USARTX,
config: impl Into<config::Config>,
prec: rec::$Rec,
clocks: &CoreClocks
$(, $synchronous: bool)?
) -> Result<Self, config::InvalidConfig>
{
// Enable clock for USART and reset
prec.enable().reset();
let ker_ck = Self::kernel_clk_unwrap(clocks);
let mut serial = Serial { usart, ker_ck };
let config = config.into();
serial.usart.cr1.reset();
// If synchronous mode is supported, check that it is not
// enabled alongside half duplex mode
$(
if config.halfduplex & $synchronous {
return Err(config::InvalidConfig);
}
)?
serial.configure(&config $(, $synchronous )?);
Ok(serial)
}
/// Runs the serial port configuration process
///
/// The serial port must be disabled when called.
fn configure(&mut self, config: &config::Config $(, $synchronous: bool)?) {
use crate::stm32::usart1::cr2::STOP_A as STOP;
use self::config::*;
// Prescaler not used for now
let usart_ker_ck_presc = self.ker_ck;
self.usart.presc.reset();
// Calculate baudrate divisor
let usartdiv = usart_ker_ck_presc / config.baudrate;
assert!(usartdiv <= 65_536);
// 16 times oversampling, OVER8 = 0
let brr = usartdiv as u16;
self.usart.brr.write(|w| { w.brr().bits(brr) });
// Reset registers to disable advanced USART features
self.usart.cr2.reset();
self.usart.cr3.reset();
// RXFIFO threshold
let fifo_threshold_bits = match config.rxfifothreshold {
FifoThreshold::Eighth => 0,
FifoThreshold::Quarter => 1,
FifoThreshold::Half => 2,
FifoThreshold::ThreeQuarter => 3,
FifoThreshold::SevenEighth => 4,
FifoThreshold::Full => 5,
};
unsafe {
self.usart.cr3.modify(|_, w| w.rxftcfg().bits(fifo_threshold_bits));
}
// TXFIFO threashold
let fifo_threshold_bits = match config.txfifothreshold {
FifoThreshold::Eighth => 0,
FifoThreshold::Quarter => 1,
FifoThreshold::Half => 2,
FifoThreshold::ThreeQuarter => 3,
FifoThreshold::SevenEighth => 4,
FifoThreshold::Full => 5,
};
unsafe {
self.usart.cr3.modify(|_, w| w.txftcfg().bits(fifo_threshold_bits));
}
// Configure half-duplex mode
self.usart.cr3.modify(|_, w| {
w.hdsel().variant(if config.halfduplex {
HDSEL_A::Selected
} else {
HDSEL_A::NotSelected
})
});
// Configure serial mode
self.usart.cr2.write(|w| {
w.stop().variant(match config.stopbits {
StopBits::Stop0p5 => STOP::Stop0p5,
StopBits::Stop1 => STOP::Stop1,
StopBits::Stop1p5 => STOP::Stop1p5,
StopBits::Stop2 => STOP::Stop2,
});
w.msbfirst().variant(match config.bitorder {
BitOrder::LsbFirst => MSBFIRST_A::Lsb,
BitOrder::MsbFirst => MSBFIRST_A::Msb,
});
w.swap().bit(config.swaptxrx);
w.rxinv().variant(if config.invertrx {
RXINV_A::Inverted
} else {
RXINV_A::Standard
});
w.txinv().variant(if config.inverttx {
TXINV_A::Inverted
} else {
TXINV_A::Standard
});
// If synchronous mode is not supported, these bits are
// reserved and must be kept at reset value
$(
w.lbcl().variant(if config.lastbitclockpulse {
LBCL_A::Output
} else {
LBCL_A::NotOutput
});
w.clken().variant(if $synchronous {
CLKEN_A::Enabled
} else {
CLKEN_A::Disabled
});
w.cpol().variant(match config.clockpolarity {
ClockPolarity::IdleHigh =>CPOL_A::High,
ClockPolarity::IdleLow =>CPOL_A::Low
});
w.cpha().variant(match config.clockphase {
ClockPhase::First => CPHA_A::First,
ClockPhase::Second => CPHA_A::Second
});
)?
w
});
// Enable transmission and receiving and configure frame
// Retain enabled events
self.usart.cr1.modify(|_, w| {
w.fifoen()
.set_bit() // FIFO mode enabled
.over8()
.oversampling16() // Oversampling by 16
.ue()
.enabled()
.te()
.enabled()
.re()
.enabled()
.m1()
.clear_bit()
.m0()
.variant(match config.parity {
Parity::ParityNone => M0::Bit8,
_ => M0::Bit9,
}).pce()
.variant(match config.parity {
Parity::ParityNone => PCE::Disabled,
_ => PCE::Enabled,
}).ps()
.variant(match config.parity {
Parity::ParityOdd => PS::Odd,
_ => PS::Even,
})
});
}
/// Applies the configuration to the serial port.
///
/// Ensure that the serial port is not transmitting data when calling this method.
///
/// # Panics
///
/// Panics if DMA Rx or Tx are enabled.
pub fn reconfigure(&mut self, config: impl Into<config::Config> $(, $synchronous: bool)?) {
if self.dma_rx_enabled() || self.dma_tx_enabled() {
panic!("Cannot reconfigure serial while DMA enabled");
}
self.usart.cr1.modify(|_, w| w.ue().disabled());
let config = config.into();
self.configure(&config $(, $synchronous )?);
}
/// Enables the Rx DMA stream.
pub fn enable_dma_rx(&mut self) {
self.usart.cr3.modify(|_, w| w.dmar().set_bit());
}
/// Disables the Rx DMA stream.
pub fn disable_dma_rx(&mut self) {
self.usart.cr3.modify(|_, w| w.dmar().clear_bit());
}
/// Returns `true` if the Rx DMA stream is enabled.
pub fn dma_rx_enabled(&self) -> bool {
self.usart.cr3.read().dmar().bit_is_set()
}
/// Enables the Tx DMA stream.
pub fn enable_dma_tx(&mut self) {
self.usart.cr3.modify(|_, w| w.dmat().set_bit());
}
/// Disables the Tx DMA stream.
pub fn disable_dma_tx(&mut self) {
self.usart.cr3.modify(|_, w| w.dmat().clear_bit());
}
/// Returns `true` if the Tx DMA stream is enabled.
pub fn dma_tx_enabled(&self) -> bool {
self.usart.cr3.read().dmat().bit_is_set()
}
/// Starts listening for an interrupt event
pub fn listen(&mut self, event: Event) {
match event {
Event::Rxne => {
self.usart.cr1.modify(|_, w| w.rxneie().enabled())
},
Event::Txe => {
self.usart.cr1.modify(|_, w| w.txeie().enabled())
},
Event::Idle => {
self.usart.cr1.modify(|_, w| w.idleie().enabled())
},
Event::Txftie => {
self.usart.cr3.modify(|_, w| w.txftie().set_bit())
},
Event::Rxftie => {
self.usart.cr3.modify(|_, w| w.rxftie().set_bit())
},
}
}
/// Stop listening for an interrupt event
pub fn unlisten(&mut self, event: Event) {
match event {
Event::Rxne => {
self.usart.cr1.modify(|_, w| w.rxneie().disabled())
},
Event::Txe => {
self.usart.cr1.modify(|_, w| w.txeie().disabled())
},
Event::Idle => {
self.usart.cr1.modify(|_, w| w.idleie().disabled())
},
Event::Txftie => {
self.usart.cr3.modify(|_, w| w.txftie().clear_bit())
},
Event::Rxftie => {
self.usart.cr3.modify(|_, w| w.rxftie().clear_bit())
},
}
let _ = self.usart.cr1.read();
let _ = self.usart.cr1.read(); // Delay 2 peripheral clocks
}
/// Return true if the line idle status is set
///
/// The line idle status bit is set when the peripheral detects the receive line is idle.
/// The bit is cleared by software, by calling `clear_idle()`.
pub fn is_idle(&self) -> bool {
unsafe { (*$USARTX::ptr()).isr.read().idle().bit_is_set() }
}
/// Clear the line idle status bit
pub fn clear_idle(&mut self) {
unsafe { (*$USARTX::ptr()).icr.write(|w| w.idlecf().set_bit()) }
let _ = self.usart.isr.read();
let _ = self.usart.isr.read(); // Delay 2 peripheral clocks
}
/// Return true if the line busy status is set
///
/// The busy status bit is set when there is communication active on the receive line,
/// and reset at the end of reception.
pub fn is_busy(&self) -> bool {
unsafe { (*$USARTX::ptr()).isr.read().busy().bit_is_set() }
}
/// Return true if the tx register is empty (and can accept data)
pub fn is_txe(&self) -> bool {
unsafe { (*$USARTX::ptr()).isr.read().txe().bit_is_set() }
}
/// Return true if the rx register is not empty (and can be read)
pub fn is_rxne(&self) -> bool {
unsafe { (*$USARTX::ptr()).isr.read().rxne().bit_is_set() }
}
/// Splits the [`Serial`] struct into transmit ([`Tx`]) and receive ([`Rx`]) parts which can be used
/// separately.
pub fn split(self) -> (Tx<$USARTX>, Rx<$USARTX>) {
(
Tx {
_usart: PhantomData,
},
Rx {
_usart: PhantomData,
ker_ck: self.ker_ck,
},
)
}
/// Combines the [`Tx`] and [`Rx`] structs from [`Serial::split()`] into a [`Serial`]
#[allow(unused_variables)]
pub fn join(tx: Tx<$USARTX>, rx: Rx<$USARTX>) -> Self {
assert_eq!(core::mem::size_of::<$USARTX>(), 0);
Self {
usart: unsafe { core::mem::zeroed::<$USARTX>() },
ker_ck: rx.ker_ck,
}
}
/// Releases the USART peripheral
pub fn release(self) -> $USARTX {
// Wait until both TXFIFO and shift register are empty
while self.usart.isr.read().tc().bit_is_clear() {}
self.usart
}
/// Returns a reference to the inner peripheral
pub fn inner(&self) -> &$USARTX {
&self.usart
}
/// Returns a mutable reference to the inner peripheral
pub fn inner_mut(&mut self) -> &mut $USARTX {
&mut self.usart
}
}
impl SerialExt<$USARTX> for $USARTX {
type Rec = rec::$Rec;
fn serial<P: Pins<$USARTX>>(self,
_pins: P,
config: impl Into<config::Config>,
prec: rec::$Rec,
clocks: &CoreClocks
) -> Result<Serial<$USARTX>, config::InvalidConfig>
{
Serial::$usartX(
self, config, prec, clocks
$(, replace_expr!($synchronous P::SYNCHRONOUS))?
)
}
fn serial_unchecked(self,
config: impl Into<config::Config>,
prec: rec::$Rec,
clocks: &CoreClocks,
#[allow(unused)]
synchronous: bool,
) -> Result<Serial<$USARTX>, config::InvalidConfig>
{
Serial::$usartX(
self, config, prec, clocks
$(, replace_expr!($synchronous synchronous))?
)
}
}
impl serial::Read<u8> for Serial<$USARTX> {
type Error = Error;
fn read(&mut self) -> nb::Result<u8, Error> {
let mut rx: Rx<$USARTX> = Rx {
_usart: PhantomData,
ker_ck: self.ker_ck,
};
rx.read()
}
}
impl serial::Read<u8> for Rx<$USARTX> {
type Error = Error;
fn read(&mut self) -> nb::Result<u8, Error> {
// NOTE(unsafe) atomic read with no side effects
let isr = unsafe { (*$USARTX::ptr()).isr.read() };
Err(if isr.pe().bit_is_set() {
unsafe { (*$USARTX::ptr()).icr.write(|w| w.pecf().clear() );};
nb::Error::Other(Error::Parity)
} else if isr.fe().bit_is_set() {
unsafe { (*$USARTX::ptr()).icr.write(|w| w.fecf().clear() );};
nb::Error::Other(Error::Framing)
} else if isr.nf().bit_is_set() {
unsafe { (*$USARTX::ptr()).icr.write(|w| w.ncf().clear() );};
nb::Error::Other(Error::Noise)
} else if isr.ore().bit_is_set() {
unsafe { (*$USARTX::ptr()).icr.write(|w| w.orecf().clear() );};
nb::Error::Other(Error::Overrun)
} else if isr.rxne().bit_is_set() {
// NOTE(read_volatile) see `write_volatile` below
return Ok(unsafe {