1use core::fmt;
4use core::marker::PhantomData;
5
6use embedded_dma::{ReadBuffer, WriteBuffer};
7use embedded_hal_nb::nb::{Error as NbError, Result as NbResult};
8use embedded_hal_nb::serial::{ErrorKind, ErrorType, Read, Write};
9use mik32_pac::usart_0::RegisterBlock;
10use mik32_pac::{Peripherals, Usart0, Usart1};
11
12use crate::dma::{Channel as DmaChannel, ChannelId as DmaChannelId, Error as DmaError};
13use crate::gpio::{Func2Mode, Func3Mode, Pin};
14use crate::rcc::system_clock;
15
16const DEFAULT_INIT_TIMEOUT: u32 = 100_000;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum WordLength {
20 DataBits7,
21 DataBits8,
22 DataBits9,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum DuplexMode {
27 Half,
28 Full,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum SyncMode {
33 Async,
34 Sync,
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum ClockPolarity {
39 IdleLow,
40 IdleHigh,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum ClockPhase {
45 FirstEdge,
46 SecondEdge,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Parity {
51 None,
52 Even,
53 Odd,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum StopBits {
58 Stop1,
59 Stop2,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum DmaConfig {
64 None,
65 Tx,
66 Rx,
67 TxRx,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum BitOrder {
72 LsbFirst,
73 MsbFirst,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum FlowControl {
78 None,
79 Rts,
80 Cts,
81 RtsCts,
82}
83
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum RtsMode {
86 AlwaysEnabled,
87 Modem,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct ModemConfig {
92 pub dtr: bool,
93}
94
95impl ModemConfig {
96 pub const fn disabled() -> Self {
97 Self { dtr: false }
98 }
99
100 pub const fn dtr(mut self, enabled: bool) -> Self {
101 self.dtr = enabled;
102 self
103 }
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct Config {
108 pub baudrate: u32,
109 pub word_length: WordLength,
110 pub parity: Parity,
111 pub stop_bits: StopBits,
112 pub duplex_mode: DuplexMode,
113 pub sync_mode: SyncMode,
114 pub clock_polarity: ClockPolarity,
115 pub clock_phase: ClockPhase,
116 pub clock_last_bit: bool,
117 pub bit_order: BitOrder,
118 pub data_inversion: bool,
119 pub tx_inversion: bool,
120 pub rx_inversion: bool,
121 pub swap_pins: bool,
122 pub loopback: bool,
123 pub tx_break: bool,
124 pub overwrite: bool,
125 pub flow_control: FlowControl,
126 pub rts_mode: RtsMode,
127 pub modem: ModemConfig,
128 pub dma: DmaConfig,
129 pub init_timeout: u32,
130}
131
132impl Config {
133 pub const fn default() -> Self {
134 Self {
135 baudrate: 115_200,
136 word_length: WordLength::DataBits8,
137 parity: Parity::None,
138 stop_bits: StopBits::Stop1,
139 duplex_mode: DuplexMode::Full,
140 sync_mode: SyncMode::Async,
141 clock_polarity: ClockPolarity::IdleLow,
142 clock_phase: ClockPhase::FirstEdge,
143 clock_last_bit: false,
144 bit_order: BitOrder::LsbFirst,
145 data_inversion: false,
146 tx_inversion: false,
147 rx_inversion: false,
148 swap_pins: false,
149 loopback: false,
150 tx_break: false,
151 overwrite: false,
152 flow_control: FlowControl::None,
153 rts_mode: RtsMode::AlwaysEnabled,
154 modem: ModemConfig::disabled(),
155 dma: DmaConfig::None,
156 init_timeout: DEFAULT_INIT_TIMEOUT,
157 }
158 }
159
160 pub const fn baudrate(mut self, baudrate: u32) -> Self {
161 self.baudrate = baudrate;
162 self
163 }
164
165 pub const fn word_length(mut self, word_length: WordLength) -> Self {
166 self.word_length = word_length;
167 self
168 }
169
170 pub const fn parity(mut self, parity: Parity) -> Self {
171 self.parity = parity;
172 self
173 }
174
175 pub const fn stop_bits(mut self, stop_bits: StopBits) -> Self {
176 self.stop_bits = stop_bits;
177 self
178 }
179
180 pub const fn duplex_mode(mut self, duplex_mode: DuplexMode) -> Self {
181 self.duplex_mode = duplex_mode;
182 self
183 }
184
185 pub const fn sync_mode(mut self, sync_mode: SyncMode) -> Self {
186 self.sync_mode = sync_mode;
187 self
188 }
189
190 pub const fn clock_polarity(mut self, polarity: ClockPolarity) -> Self {
191 self.clock_polarity = polarity;
192 self
193 }
194
195 pub const fn clock_phase(mut self, phase: ClockPhase) -> Self {
196 self.clock_phase = phase;
197 self
198 }
199
200 pub const fn clock_last_bit(mut self, enabled: bool) -> Self {
201 self.clock_last_bit = enabled;
202 self
203 }
204
205 pub const fn bit_order(mut self, bit_order: BitOrder) -> Self {
206 self.bit_order = bit_order;
207 self
208 }
209
210 pub const fn data_inversion(mut self, enabled: bool) -> Self {
211 self.data_inversion = enabled;
212 self
213 }
214
215 pub const fn tx_inversion(mut self, enabled: bool) -> Self {
216 self.tx_inversion = enabled;
217 self
218 }
219
220 pub const fn rx_inversion(mut self, enabled: bool) -> Self {
221 self.rx_inversion = enabled;
222 self
223 }
224
225 pub const fn swap_pins(mut self, enabled: bool) -> Self {
226 self.swap_pins = enabled;
227 self
228 }
229
230 pub const fn loopback(mut self, enabled: bool) -> Self {
231 self.loopback = enabled;
232 self
233 }
234
235 pub const fn tx_break(mut self, enabled: bool) -> Self {
236 self.tx_break = enabled;
237 self
238 }
239
240 pub const fn overwrite(mut self, enabled: bool) -> Self {
241 self.overwrite = enabled;
242 self
243 }
244
245 pub const fn flow_control(mut self, flow_control: FlowControl) -> Self {
246 self.flow_control = flow_control;
247 self
248 }
249
250 pub const fn rts_mode(mut self, mode: RtsMode) -> Self {
251 self.rts_mode = mode;
252 self
253 }
254
255 pub const fn modem(mut self, modem: ModemConfig) -> Self {
256 self.modem = modem;
257 self
258 }
259
260 pub const fn dma(mut self, dma: DmaConfig) -> Self {
261 self.dma = dma;
262 self
263 }
264
265 pub const fn init_timeout(mut self, timeout: u32) -> Self {
266 self.init_timeout = timeout;
267 self
268 }
269
270 pub const fn validate(&self) -> Result<(), ConfigError> {
271 if self.baudrate == 0 {
272 return Err(ConfigError::ZeroBaudrate);
273 }
274 if self.init_timeout == 0 {
275 return Err(ConfigError::ZeroInitTimeout);
276 }
277
278 Ok(())
279 }
280}
281
282impl Default for Config {
283 fn default() -> Self {
284 Self::default()
285 }
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub enum ConfigError {
290 ZeroBaudrate,
291 ZeroInitTimeout,
292 BaudrateTooHigh,
293 BaudrateTooLow,
294 DedicatedConstructorRequired,
295}
296
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub enum InitErrorKind {
299 InvalidConfig(ConfigError),
300 PeripheralNotReady,
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub enum DmaTransferError {
305 Dma(DmaError),
306 InvalidWordLength,
307 WordOutOfRange,
308}
309
310impl From<DmaError> for DmaTransferError {
311 fn from(error: DmaError) -> Self {
312 Self::Dma(error)
313 }
314}
315
316pub struct DmaTransferFailure<PERIPHERAL, CHANNEL, BUFFER> {
317 pub error: DmaTransferError,
318 pub peripheral: PERIPHERAL,
319 pub channel: CHANNEL,
320 pub buffer: BUFFER,
321}
322
323impl<PERIPHERAL, CHANNEL, BUFFER> DmaTransferFailure<PERIPHERAL, CHANNEL, BUFFER> {
324 pub fn into_parts(self) -> (DmaTransferError, PERIPHERAL, CHANNEL, BUFFER) {
325 (self.error, self.peripheral, self.channel, self.buffer)
326 }
327}
328
329impl<PERIPHERAL, CHANNEL, BUFFER> fmt::Debug for DmaTransferFailure<PERIPHERAL, CHANNEL, BUFFER> {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 f.debug_struct("DmaTransferFailure")
332 .field("error", &self.error)
333 .finish_non_exhaustive()
334 }
335}
336
337pub struct InitError<UART, TXPIN, RXPIN> {
338 pub uart: UART,
339 pub pins: (TXPIN, RXPIN),
340 pub error: InitErrorKind,
341}
342
343impl<UART, TXPIN, RXPIN> InitError<UART, TXPIN, RXPIN> {
344 pub fn into_parts(self) -> (UART, (TXPIN, RXPIN), InitErrorKind) {
345 (self.uart, self.pins, self.error)
346 }
347}
348
349impl<UART, TXPIN, RXPIN> fmt::Debug for InitError<UART, TXPIN, RXPIN> {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 f.debug_struct("InitError")
352 .field("error", &self.error)
353 .finish_non_exhaustive()
354 }
355}
356
357pub struct ModeInitError<UART, PINS> {
358 pub uart: UART,
359 pub pins: PINS,
360 pub error: InitErrorKind,
361}
362
363impl<UART, PINS> ModeInitError<UART, PINS> {
364 pub fn into_parts(self) -> (UART, PINS, InitErrorKind) {
365 (self.uart, self.pins, self.error)
366 }
367}
368
369impl<UART, PINS> fmt::Debug for ModeInitError<UART, PINS> {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 f.debug_struct("ModeInitError")
372 .field("error", &self.error)
373 .finish_non_exhaustive()
374 }
375}
376
377pub trait TxPin<UART> {}
378pub trait RxPin<UART> {}
379pub trait ClockPin<UART> {}
380pub trait HalfDuplexPin<UART> {}
381pub trait RtsPin<UART> {}
382pub trait CtsPin<UART> {}
383pub trait DtrPin<UART> {}
384pub trait DsrPin<UART> {}
385pub trait DcdPin<UART> {}
386pub trait RiPin<UART> {}
387pub trait DdisPin<UART> {}
388
389pub trait FlowControlPins<UART> {
390 const FLOW_CONTROL: FlowControl;
391}
392
393pub struct CtsOnly<CTS>(pub CTS);
394
395impl<UART> FlowControlPins<UART> for () {
396 const FLOW_CONTROL: FlowControl = FlowControl::None;
397}
398
399impl<UART, RTS> FlowControlPins<UART> for (RTS,)
400where
401 RTS: RtsPin<UART>,
402{
403 const FLOW_CONTROL: FlowControl = FlowControl::Rts;
404}
405
406impl<UART, RTS, CTS> FlowControlPins<UART> for (RTS, CTS)
407where
408 RTS: RtsPin<UART>,
409 CTS: CtsPin<UART>,
410{
411 const FLOW_CONTROL: FlowControl = FlowControl::RtsCts;
412}
413
414impl<UART, CTS> FlowControlPins<UART> for CtsOnly<CTS>
415where
416 CTS: CtsPin<UART>,
417{
418 const FLOW_CONTROL: FlowControl = FlowControl::Cts;
419}
420
421pub trait ModemPins<UART> {}
422
423impl<UART> ModemPins<UART> for () {}
424
425impl TxPin<Usart0> for Pin<0, 6, Func2Mode> {}
426impl RxPin<Usart0> for Pin<0, 5, Func2Mode> {}
427impl CtsPin<Usart0> for Pin<0, 7, Func2Mode> {}
428impl RtsPin<Usart0> for Pin<0, 8, Func2Mode> {}
429impl DdisPin<Usart0> for Pin<1, 6, Func3Mode> {}
430impl DtrPin<Usart0> for Pin<1, 12, Func3Mode> {}
431impl DcdPin<Usart0> for Pin<1, 13, Func3Mode> {}
432impl DsrPin<Usart0> for Pin<1, 14, Func3Mode> {}
433impl RiPin<Usart0> for Pin<1, 15, Func3Mode> {}
434
435impl TxPin<Usart1> for Pin<1, 9, Func2Mode> {}
436impl RxPin<Usart1> for Pin<1, 8, Func2Mode> {}
437impl CtsPin<Usart1> for Pin<1, 10, Func2Mode> {}
438impl RtsPin<Usart1> for Pin<1, 11, Func2Mode> {}
439impl ClockPin<Usart0> for Pin<1, 5, Func3Mode> {}
440impl ClockPin<Usart1> for Pin<2, 6, Func3Mode> {}
441impl DtrPin<Usart1> for Pin<2, 0, Func3Mode> {}
442impl DcdPin<Usart1> for Pin<2, 1, Func3Mode> {}
443impl DsrPin<Usart1> for Pin<2, 2, Func3Mode> {}
444impl RiPin<Usart1> for Pin<2, 3, Func3Mode> {}
445impl DdisPin<Usart1> for Pin<2, 7, Func3Mode> {}
446impl HalfDuplexPin<Usart0> for Pin<0, 6, Func2Mode> {}
447impl HalfDuplexPin<Usart1> for Pin<1, 9, Func2Mode> {}
448
449impl<UART, DTR> ModemPins<UART> for (DTR,) where DTR: DtrPin<UART> {}
450
451impl<UART, DTR, DSR, DCD, RI, DDIS> ModemPins<UART> for (DTR, DSR, DCD, RI, DDIS)
452where
453 DTR: DtrPin<UART>,
454 DSR: DsrPin<UART>,
455 DCD: DcdPin<UART>,
456 RI: RiPin<UART>,
457 DDIS: DdisPin<UART>,
458{
459}
460
461mod sealed {
462 pub trait Sealed {}
463
464 impl Sealed for mik32_pac::Usart0 {}
465 impl Sealed for mik32_pac::Usart1 {}
466}
467
468pub trait Instance: sealed::Sealed {
469 fn ptr() -> *const RegisterBlock;
470 fn enable_clock();
471 const DMA_REQUEST: u32;
472}
473
474impl Instance for Usart0 {
475 const DMA_REQUEST: u32 = 0;
476 #[inline(always)]
477 fn ptr() -> *const RegisterBlock {
478 Usart0::ptr()
479 }
480
481 #[inline(always)]
482 fn enable_clock() {
483 let p = unsafe { Peripherals::steal() };
484 p.pm.clk_apb_p_set().modify(|_, w| w.uart_0().enable());
485 }
486}
487
488impl Instance for Usart1 {
489 const DMA_REQUEST: u32 = 1;
490 #[inline(always)]
491 fn ptr() -> *const RegisterBlock {
492 Usart1::ptr()
493 }
494
495 #[inline(always)]
496 fn enable_clock() {
497 let p = unsafe { Peripherals::steal() };
498 p.pm.clk_apb_p_set().modify(|_, w| w.uart_1().enable());
499 }
500}
501
502pub struct Serial<UART, TXPIN, RXPIN>
503where
504 UART: Instance,
505 TXPIN: TxPin<UART>,
506 RXPIN: RxPin<UART>,
507{
508 uart: UART,
509 pins: (TXPIN, RXPIN),
510 word_length: WordLength,
511}
512
513pub struct TxOnly<UART, TXPIN>
514where
515 UART: Instance,
516 TXPIN: TxPin<UART>,
517{
518 tx: Tx<UART, TXPIN, Owned>,
519}
520
521pub struct RxOnly<UART, RXPIN>
522where
523 UART: Instance,
524 RXPIN: RxPin<UART>,
525{
526 rx: Rx<UART, RXPIN, Owned>,
527}
528
529pub struct FlowControlSerial<UART, TXPIN, RXPIN, FLOWPINS>
530where
531 UART: Instance,
532 TXPIN: TxPin<UART>,
533 RXPIN: RxPin<UART>,
534 FLOWPINS: FlowControlPins<UART>,
535{
536 serial: Serial<UART, TXPIN, RXPIN>,
537 flow_pins: FLOWPINS,
538}
539
540pub struct ModemSerial<UART, TXPIN, RXPIN, MODEMPINS>
541where
542 UART: Instance,
543 TXPIN: TxPin<UART>,
544 RXPIN: RxPin<UART>,
545 MODEMPINS: ModemPins<UART>,
546{
547 serial: Serial<UART, TXPIN, RXPIN>,
548 modem_pins: MODEMPINS,
549}
550
551pub struct Owned;
552pub struct Borrowed;
553
554pub struct Tx<UART: Instance, TXPIN = (), OWNER = Owned> {
555 uart: Option<UART>,
556 pin: TXPIN,
557 _uart: PhantomData<UART>,
558 _owner: PhantomData<OWNER>,
559 word_length: WordLength,
560}
561
562pub struct Rx<UART: Instance, RXPIN = (), OWNER = Owned> {
563 uart: Option<UART>,
564 pin: RXPIN,
565 _uart: PhantomData<UART>,
566 _owner: PhantomData<OWNER>,
567 word_length: WordLength,
568}
569
570pub struct TxDmaTransfer<UART: Instance, TXPIN, OWNER, CHANNEL: DmaChannelId, BUFFER> {
581 tx: Option<Tx<UART, TXPIN, OWNER>>,
582 channel: Option<DmaChannel<CHANNEL>>,
583 buffer: Option<BUFFER>,
584 request_was_enabled: bool,
585}
586
587pub struct RxDmaTransfer<UART: Instance, RXPIN, OWNER, CHANNEL: DmaChannelId, BUFFER> {
598 rx: Option<Rx<UART, RXPIN, OWNER>>,
599 channel: Option<DmaChannel<CHANNEL>>,
600 buffer: Option<BUFFER>,
601 request_was_enabled: bool,
602}
603
604pub struct SynchronousSerial<UART, TXPIN, RXPIN, CLOCKPIN>
605where
606 UART: Instance,
607 TXPIN: TxPin<UART>,
608 RXPIN: RxPin<UART>,
609 CLOCKPIN: ClockPin<UART>,
610{
611 serial: Serial<UART, TXPIN, RXPIN>,
612 clock: CLOCKPIN,
613}
614
615pub struct HalfDuplex<UART, PIN>
616where
617 UART: Instance,
618 PIN: HalfDuplexPin<UART>,
619{
620 uart: UART,
621 pin: PIN,
622 word_length: WordLength,
623}
624
625impl<UART, TXPIN, RXPIN> Serial<UART, TXPIN, RXPIN>
626where
627 UART: Instance,
628 TXPIN: TxPin<UART>,
629 RXPIN: RxPin<UART>,
630{
631 pub fn new(
632 uart: UART,
633 pins: (TXPIN, RXPIN),
634 config: Config,
635 ) -> Result<Self, InitError<UART, TXPIN, RXPIN>> {
636 if config.duplex_mode != DuplexMode::Full
637 || config.sync_mode != SyncMode::Async
638 || config.flow_control != FlowControl::None
639 || config.modem.dtr
640 {
641 return Err(InitError {
642 uart,
643 pins,
644 error: InitErrorKind::InvalidConfig(ConfigError::DedicatedConstructorRequired),
645 });
646 }
647 Self::new_configured(uart, pins, config)
648 }
649
650 fn new_configured(
651 uart: UART,
652 pins: (TXPIN, RXPIN),
653 config: Config,
654 ) -> Result<Self, InitError<UART, TXPIN, RXPIN>> {
655 if let Err(error) = config.validate() {
656 return Err(InitError {
657 uart,
658 pins,
659 error: InitErrorKind::InvalidConfig(error),
660 });
661 }
662
663 let baudrate_divisor = match calc_baudrate_divisor(config.baudrate) {
664 Ok(divisor) => divisor,
665 Err(error) => {
666 return Err(InitError {
667 uart,
668 pins,
669 error: InitErrorKind::InvalidConfig(error),
670 });
671 }
672 };
673
674 UART::enable_clock();
675
676 let serial = Self {
677 uart,
678 pins,
679 word_length: config.word_length,
680 };
681 if let Err(error) = configure_uart::<UART>(config, baudrate_divisor, true, true) {
682 serial.regs().control1().modify(|_, w| w.ue().disable());
683 let Self {
684 uart,
685 pins,
686 word_length: _,
687 } = serial;
688 return Err(InitError { uart, pins, error });
689 }
690
691 Ok(serial)
692 }
693
694 pub fn release(self) -> (UART, (TXPIN, RXPIN)) {
695 regs::<UART>().control1().modify(|_, w| w.ue().disable());
696 (self.uart, self.pins)
697 }
698
699 pub fn split(self) -> (Tx<UART, TXPIN, Owned>, Rx<UART, RXPIN, Borrowed>) {
700 let Self {
701 uart,
702 pins: (tx_pin, rx_pin),
703 word_length,
704 } = self;
705
706 (
707 Tx {
708 uart: Some(uart),
709 pin: tx_pin,
710 _uart: PhantomData,
711 _owner: PhantomData,
712 word_length,
713 },
714 Rx {
715 uart: None,
716 pin: rx_pin,
717 _uart: PhantomData,
718 _owner: PhantomData,
719 word_length,
720 },
721 )
722 }
723
724 pub fn reunite(
725 tx: Tx<UART, TXPIN, Owned>,
726 rx: Rx<UART, RXPIN, Borrowed>,
727 ) -> Serial<UART, TXPIN, RXPIN> {
728 let Tx {
729 uart,
730 pin: tx_pin,
731 word_length,
732 ..
733 } = tx;
734 let Rx { pin: rx_pin, .. } = rx;
735 Serial {
736 uart: uart.expect("split Tx missing USART owner"),
737 pins: (tx_pin, rx_pin),
738 word_length,
739 }
740 }
741
742 #[inline(always)]
743 fn regs(&self) -> &RegisterBlock {
744 unsafe { &*UART::ptr() }
745 }
746}
747
748impl<UART, TXPIN> TxOnly<UART, TXPIN>
749where
750 UART: Instance,
751 TXPIN: TxPin<UART>,
752{
753 pub fn new(uart: UART, pin: TXPIN, config: Config) -> Result<Self, ModeInitError<UART, TXPIN>> {
754 let tx = new_tx_only(uart, pin, config)?;
755 Ok(Self { tx })
756 }
757
758 pub fn split(self) -> Tx<UART, TXPIN, Owned> {
759 self.tx
760 }
761
762 pub fn release(self) -> (UART, TXPIN) {
763 self.tx.release()
764 }
765}
766
767impl<UART, RXPIN> RxOnly<UART, RXPIN>
768where
769 UART: Instance,
770 RXPIN: RxPin<UART>,
771{
772 pub fn new(uart: UART, pin: RXPIN, config: Config) -> Result<Self, ModeInitError<UART, RXPIN>> {
773 let rx = new_rx_only(uart, pin, config)?;
774 Ok(Self { rx })
775 }
776
777 pub fn split(self) -> Rx<UART, RXPIN, Owned> {
778 self.rx
779 }
780
781 pub fn release(self) -> (UART, RXPIN) {
782 self.rx.release()
783 }
784}
785
786impl<UART, TXPIN, RXPIN, FLOWPINS> FlowControlSerial<UART, TXPIN, RXPIN, FLOWPINS>
787where
788 UART: Instance,
789 TXPIN: TxPin<UART>,
790 RXPIN: RxPin<UART>,
791 FLOWPINS: FlowControlPins<UART>,
792{
793 pub fn new(
794 uart: UART,
795 pins: (TXPIN, RXPIN, FLOWPINS),
796 mut config: Config,
797 ) -> Result<Self, ModeInitError<UART, (TXPIN, RXPIN, FLOWPINS)>> {
798 config.flow_control = FLOWPINS::FLOW_CONTROL;
799 let (tx, rx, flow_pins) = pins;
800 match Serial::new_configured(uart, (tx, rx), config) {
801 Ok(serial) => Ok(Self { serial, flow_pins }),
802 Err(error) => {
803 let (uart, (tx, rx), error) = error.into_parts();
804 Err(ModeInitError {
805 uart,
806 pins: (tx, rx, flow_pins),
807 error,
808 })
809 }
810 }
811 }
812
813 pub fn release(self) -> (UART, (TXPIN, RXPIN, FLOWPINS)) {
814 let (uart, (tx, rx)) = self.serial.release();
815 (uart, (tx, rx, self.flow_pins))
816 }
817
818 pub fn split(self) -> (Tx<UART, TXPIN, Owned>, Rx<UART, RXPIN, Borrowed>, FLOWPINS) {
819 let flow_pins = self.flow_pins;
820 let (tx, rx) = self.serial.split();
821 (tx, rx, flow_pins)
822 }
823}
824
825impl<UART, TXPIN, RXPIN, MODEMPINS> ModemSerial<UART, TXPIN, RXPIN, MODEMPINS>
826where
827 UART: Instance,
828 TXPIN: TxPin<UART>,
829 RXPIN: RxPin<UART>,
830 MODEMPINS: ModemPins<UART>,
831{
832 pub fn new(
833 uart: UART,
834 pins: (TXPIN, RXPIN, MODEMPINS),
835 config: Config,
836 ) -> Result<Self, ModeInitError<UART, (TXPIN, RXPIN, MODEMPINS)>> {
837 let (tx, rx, modem_pins) = pins;
838 match Serial::new_configured(uart, (tx, rx), config) {
839 Ok(serial) => Ok(Self { serial, modem_pins }),
840 Err(error) => {
841 let (uart, (tx, rx), error) = error.into_parts();
842 Err(ModeInitError {
843 uart,
844 pins: (tx, rx, modem_pins),
845 error,
846 })
847 }
848 }
849 }
850
851 pub fn set_dtr(&mut self, ready: bool) {
852 regs::<UART>().modem().modify(|_, w| w.dtr().bit(ready));
853 }
854
855 pub fn is_dtr_ready(&self) -> bool {
856 regs::<UART>().modem().read().dtr().bit_is_set()
857 }
858
859 pub fn is_dsr_high(&self) -> bool {
860 regs::<UART>().modem().read().dsr().bit_is_set()
861 }
862
863 pub fn dsr_changed(&self) -> bool {
864 regs::<UART>().modem().read().dsrif().bit_is_set()
865 }
866
867 pub fn clear_dsr_changed(&mut self) {
868 regs::<UART>()
869 .modem()
870 .write(|w| w.dsrif().clear_bit_by_one());
871 }
872
873 pub fn is_dcd_high(&self) -> bool {
874 regs::<UART>().modem().read().dcd().bit_is_set()
875 }
876
877 pub fn dcd_changed(&self) -> bool {
878 regs::<UART>().modem().read().dcdif().bit_is_set()
879 }
880
881 pub fn clear_dcd_changed(&mut self) {
882 regs::<UART>()
883 .modem()
884 .write(|w| w.dcdif().clear_bit_by_one());
885 }
886
887 pub fn is_ri_high(&self) -> bool {
888 regs::<UART>().modem().read().ri().bit_is_set()
889 }
890
891 pub fn ri_changed(&self) -> bool {
892 regs::<UART>().modem().read().riif().bit_is_set()
893 }
894
895 pub fn clear_ri_changed(&mut self) {
896 regs::<UART>()
897 .modem()
898 .write(|w| w.riif().clear_bit_by_one());
899 }
900
901 pub fn release(self) -> (UART, (TXPIN, RXPIN, MODEMPINS)) {
902 let (uart, (tx, rx)) = self.serial.release();
903 (uart, (tx, rx, self.modem_pins))
904 }
905
906 pub fn split(self) -> (Tx<UART, TXPIN, Owned>, Rx<UART, RXPIN, Borrowed>, MODEMPINS) {
907 let modem_pins = self.modem_pins;
908 let (tx, rx) = self.serial.split();
909 (tx, rx, modem_pins)
910 }
911}
912
913fn new_tx_only<UART, TXPIN>(
914 uart: UART,
915 pin: TXPIN,
916 mut config: Config,
917) -> Result<Tx<UART, TXPIN, Owned>, ModeInitError<UART, TXPIN>>
918where
919 UART: Instance,
920 TXPIN: TxPin<UART>,
921{
922 if let Err(error) = config.validate() {
923 return Err(ModeInitError {
924 uart,
925 pins: pin,
926 error: InitErrorKind::InvalidConfig(error),
927 });
928 }
929
930 let baudrate_divisor = match calc_baudrate_divisor(config.baudrate) {
931 Ok(divisor) => divisor,
932 Err(error) => {
933 return Err(ModeInitError {
934 uart,
935 pins: pin,
936 error: InitErrorKind::InvalidConfig(error),
937 });
938 }
939 };
940
941 config.duplex_mode = DuplexMode::Full;
942 config.sync_mode = SyncMode::Async;
943 UART::enable_clock();
944
945 if let Err(error) = configure_uart::<UART>(config, baudrate_divisor, true, false) {
946 regs::<UART>().control1().modify(|_, w| w.ue().disable());
947 return Err(ModeInitError {
948 uart,
949 pins: pin,
950 error,
951 });
952 }
953
954 Ok(Tx {
955 uart: Some(uart),
956 pin,
957 _uart: PhantomData,
958 _owner: PhantomData,
959 word_length: config.word_length,
960 })
961}
962
963fn new_rx_only<UART, RXPIN>(
964 uart: UART,
965 pin: RXPIN,
966 mut config: Config,
967) -> Result<Rx<UART, RXPIN, Owned>, ModeInitError<UART, RXPIN>>
968where
969 UART: Instance,
970 RXPIN: RxPin<UART>,
971{
972 if let Err(error) = config.validate() {
973 return Err(ModeInitError {
974 uart,
975 pins: pin,
976 error: InitErrorKind::InvalidConfig(error),
977 });
978 }
979
980 let baudrate_divisor = match calc_baudrate_divisor(config.baudrate) {
981 Ok(divisor) => divisor,
982 Err(error) => {
983 return Err(ModeInitError {
984 uart,
985 pins: pin,
986 error: InitErrorKind::InvalidConfig(error),
987 });
988 }
989 };
990
991 config.duplex_mode = DuplexMode::Full;
992 config.sync_mode = SyncMode::Async;
993 UART::enable_clock();
994
995 if let Err(error) = configure_uart::<UART>(config, baudrate_divisor, false, true) {
996 regs::<UART>().control1().modify(|_, w| w.ue().disable());
997 return Err(ModeInitError {
998 uart,
999 pins: pin,
1000 error,
1001 });
1002 }
1003
1004 Ok(Rx {
1005 uart: Some(uart),
1006 pin,
1007 _uart: PhantomData,
1008 _owner: PhantomData,
1009 word_length: config.word_length,
1010 })
1011}
1012
1013impl<UART, TXPIN, RXPIN, CLOCKPIN> SynchronousSerial<UART, TXPIN, RXPIN, CLOCKPIN>
1014where
1015 UART: Instance,
1016 TXPIN: TxPin<UART>,
1017 RXPIN: RxPin<UART>,
1018 CLOCKPIN: ClockPin<UART>,
1019{
1020 pub fn new(
1021 uart: UART,
1022 pins: (TXPIN, RXPIN, CLOCKPIN),
1023 mut config: Config,
1024 ) -> Result<Self, ModeInitError<UART, (TXPIN, RXPIN, CLOCKPIN)>> {
1025 config.duplex_mode = DuplexMode::Full;
1026 config.sync_mode = SyncMode::Sync;
1027 let (tx, rx, clock) = pins;
1028
1029 match Serial::new_configured(uart, (tx, rx), config) {
1030 Ok(serial) => Ok(Self { serial, clock }),
1031 Err(error) => {
1032 let (uart, (tx, rx), error) = error.into_parts();
1033 Err(ModeInitError {
1034 uart,
1035 pins: (tx, rx, clock),
1036 error,
1037 })
1038 }
1039 }
1040 }
1041
1042 pub fn split(self) -> (Tx<UART, TXPIN, Owned>, Rx<UART, RXPIN, Borrowed>, CLOCKPIN) {
1043 let (tx, rx) = self.serial.split();
1044 (tx, rx, self.clock)
1045 }
1046
1047 pub fn release(self) -> (UART, (TXPIN, RXPIN, CLOCKPIN)) {
1048 let (uart, (tx, rx)) = self.serial.release();
1049 (uart, (tx, rx, self.clock))
1050 }
1051}
1052
1053impl<UART, PIN> HalfDuplex<UART, PIN>
1054where
1055 UART: Instance,
1056 PIN: HalfDuplexPin<UART>,
1057{
1058 pub fn new(uart: UART, pin: PIN, mut config: Config) -> Result<Self, ModeInitError<UART, PIN>> {
1059 if let Err(error) = config.validate() {
1060 return Err(ModeInitError {
1061 uart,
1062 pins: pin,
1063 error: InitErrorKind::InvalidConfig(error),
1064 });
1065 }
1066
1067 let baudrate_divisor = match calc_baudrate_divisor(config.baudrate) {
1068 Ok(divisor) => divisor,
1069 Err(error) => {
1070 return Err(ModeInitError {
1071 uart,
1072 pins: pin,
1073 error: InitErrorKind::InvalidConfig(error),
1074 });
1075 }
1076 };
1077
1078 config.duplex_mode = DuplexMode::Half;
1079 config.sync_mode = SyncMode::Async;
1080 UART::enable_clock();
1081
1082 if let Err(error) = configure_uart::<UART>(config, baudrate_divisor, true, true) {
1083 regs::<UART>().control1().modify(|_, w| w.ue().disable());
1084 return Err(ModeInitError {
1085 uart,
1086 pins: pin,
1087 error,
1088 });
1089 }
1090
1091 Ok(Self {
1092 uart,
1093 pin,
1094 word_length: config.word_length,
1095 })
1096 }
1097
1098 pub fn release(self) -> (UART, PIN) {
1099 regs::<UART>().control1().modify(|_, w| w.ue().disable());
1100 (self.uart, self.pin)
1101 }
1102}
1103
1104fn configure_uart<UART: Instance>(
1105 config: Config,
1106 baudrate_divisor: u16,
1107 enable_tx: bool,
1108 enable_rx: bool,
1109) -> Result<(), InitErrorKind> {
1110 let regs = regs::<UART>();
1111
1112 regs.control1().modify(|_, w| w.ue().disable());
1113
1114 regs.divider()
1115 .write(|w| unsafe { w.brr().bits(baudrate_divisor) });
1116
1117 regs.control1().write(|w| {
1118 w.idleie()
1119 .disable()
1120 .peie()
1121 .disable()
1122 .rxneie()
1123 .disable()
1124 .tcie()
1125 .disable()
1126 .txeie()
1127 .disable()
1128 });
1129
1130 regs.control2().write(|w| {
1131 w.lbdie()
1132 .disable()
1133 .lbm()
1134 .normal()
1135 .swap()
1136 .normal()
1137 .rxinv()
1138 .direct()
1139 .txinv()
1140 .direct()
1141 .datainv()
1142 .direct()
1143 .msbfirst()
1144 .lsb()
1145 });
1146
1147 regs.control3().write(|w| {
1148 w.eie()
1149 .disable()
1150 .ctsie()
1151 .disable()
1152 .ctse()
1153 .ignored()
1154 .rtse()
1155 .bit(false)
1156 });
1157
1158 match config.word_length {
1159 WordLength::DataBits7 => regs.control1().modify(|_, w| w.m()._7bits()),
1160 WordLength::DataBits8 => regs.control1().modify(|_, w| w.m()._8bits()),
1161 WordLength::DataBits9 => regs.control1().modify(|_, w| w.m()._9bits()),
1162 };
1163
1164 match config.parity {
1165 Parity::None => regs.control1().modify(|_, w| w.pce().disable()),
1166 Parity::Even => regs
1167 .control1()
1168 .modify(|_, w| w.pce().enable().ps().parity()),
1169 Parity::Odd => regs.control1().modify(|_, w| w.pce().enable().ps().odd()),
1170 };
1171
1172 match config.stop_bits {
1173 StopBits::Stop1 => regs.control2().modify(|_, w| w.stop_1()._1bit()),
1174 StopBits::Stop2 => regs.control2().modify(|_, w| w.stop_1()._2bits()),
1175 };
1176
1177 match config.duplex_mode {
1178 DuplexMode::Full => regs.control3().modify(|_, w| w.hdsel().duplex()),
1179 DuplexMode::Half => regs.control3().modify(|_, w| w.hdsel().half_duplex()),
1180 };
1181
1182 match config.sync_mode {
1183 SyncMode::Async => regs.control2().modify(|_, w| w.clken().asynchronous()),
1184 SyncMode::Sync => regs.control2().modify(|_, w| w.clken().synchronous()),
1185 };
1186
1187 regs.control2().modify(|_, w| {
1188 w.cpol()
1189 .bit(config.clock_polarity == ClockPolarity::IdleHigh)
1190 .cpha()
1191 .bit(config.clock_phase == ClockPhase::SecondEdge)
1192 .lbcl()
1193 .bit(config.clock_last_bit)
1194 .msbfirst()
1195 .bit(config.bit_order == BitOrder::MsbFirst)
1196 .datainv()
1197 .bit(config.data_inversion)
1198 .txinv()
1199 .bit(config.tx_inversion)
1200 .rxinv()
1201 .bit(config.rx_inversion)
1202 .swap()
1203 .bit(config.swap_pins)
1204 .lbm()
1205 .bit(config.loopback)
1206 });
1207
1208 regs.control3().modify(|_, w| {
1209 w.sbkrq()
1210 .bit(config.tx_break)
1211 .ovrdis()
1212 .bit(config.overwrite)
1213 .rtse()
1214 .bit(
1215 matches!(config.flow_control, FlowControl::Rts | FlowControl::RtsCts)
1216 && config.rts_mode == RtsMode::Modem,
1217 )
1218 .ctse()
1219 .bit(matches!(
1220 config.flow_control,
1221 FlowControl::Cts | FlowControl::RtsCts
1222 ))
1223 });
1224
1225 regs.modem().write(|w| w.dtr().bit(config.modem.dtr));
1226
1227 match config.dma {
1228 DmaConfig::None => regs
1229 .control3()
1230 .modify(|_, w| w.dmat().disable().dmar().disable()),
1231 DmaConfig::Tx => regs
1232 .control3()
1233 .modify(|_, w| w.dmat().enable().dmar().disable()),
1234 DmaConfig::Rx => regs
1235 .control3()
1236 .modify(|_, w| w.dmat().disable().dmar().enable()),
1237 DmaConfig::TxRx => regs
1238 .control3()
1239 .modify(|_, w| w.dmat().enable().dmar().enable()),
1240 };
1241
1242 regs.flags().write(|w| unsafe { w.bits(0x03ff) });
1243
1244 regs.control1()
1245 .modify(|_, w| w.te().bit(enable_tx).re().bit(enable_rx).ue().enable());
1246
1247 for _ in 0..config.init_timeout {
1248 let flags = regs.flags().read();
1249 let tx_ready = !enable_tx || flags.teack().bit_is_set();
1250 let rx_ready = !enable_rx || flags.reack().bit_is_set();
1251 if tx_ready && rx_ready {
1252 return Ok(());
1253 }
1254 core::hint::spin_loop();
1255 }
1256
1257 Err(InitErrorKind::PeripheralNotReady)
1258}
1259
1260impl<UART, TXPIN, RXPIN> ErrorType for Serial<UART, TXPIN, RXPIN>
1261where
1262 UART: Instance,
1263 TXPIN: TxPin<UART>,
1264 RXPIN: RxPin<UART>,
1265{
1266 type Error = ErrorKind;
1267}
1268
1269impl<UART: Instance, TXPIN, OWNER> ErrorType for Tx<UART, TXPIN, OWNER> {
1270 type Error = ErrorKind;
1271}
1272
1273impl<UART: Instance, TXPIN, OWNER> Tx<UART, TXPIN, OWNER> {
1274 pub fn send_break(&mut self, enabled: bool) {
1275 regs::<UART>()
1276 .control3()
1277 .modify(|_, w| w.sbkrq().bit(enabled));
1278 }
1279
1280 pub fn is_cts_high(&self) -> bool {
1281 regs::<UART>().flags().read().cts().bit_is_set()
1282 }
1283
1284 pub fn cts_changed(&self) -> bool {
1285 regs::<UART>().flags().read().ctsif().bit_is_set()
1286 }
1287
1288 pub fn clear_cts_changed(&mut self) {
1289 regs::<UART>()
1290 .flags()
1291 .write(|w| w.ctsif().clear_bit_by_one());
1292 }
1293
1294 pub fn write_dma<CHANNEL: DmaChannelId, BUFFER>(
1313 self,
1314 mut channel: DmaChannel<CHANNEL>,
1315 buffer: BUFFER,
1316 ) -> Result<
1317 TxDmaTransfer<UART, TXPIN, OWNER, CHANNEL, BUFFER>,
1318 DmaTransferFailure<Self, DmaChannel<CHANNEL>, BUFFER>,
1319 >
1320 where
1321 BUFFER: ReadBuffer<Word = u8>,
1322 {
1323 if self.word_length == WordLength::DataBits9 {
1324 return Err(DmaTransferFailure {
1325 error: DmaTransferError::InvalidWordLength,
1326 peripheral: self,
1327 channel,
1328 buffer,
1329 });
1330 }
1331
1332 let (source, length) = unsafe { buffer.read_buffer() };
1333 match dma_write_start::<UART, CHANNEL>(&mut channel, source, length, 0) {
1334 Ok(request_was_enabled) => Ok(TxDmaTransfer {
1335 tx: Some(self),
1336 channel: Some(channel),
1337 buffer: Some(buffer),
1338 request_was_enabled,
1339 }),
1340 Err(error) => Err(DmaTransferFailure {
1341 error,
1342 peripheral: self,
1343 channel,
1344 buffer,
1345 }),
1346 }
1347 }
1348
1349 pub fn write_dma_9bit<CHANNEL: DmaChannelId, BUFFER>(
1360 self,
1361 mut channel: DmaChannel<CHANNEL>,
1362 buffer: BUFFER,
1363 ) -> Result<
1364 TxDmaTransfer<UART, TXPIN, OWNER, CHANNEL, BUFFER>,
1365 DmaTransferFailure<Self, DmaChannel<CHANNEL>, BUFFER>,
1366 >
1367 where
1368 BUFFER: ReadBuffer<Word = u16>,
1369 {
1370 if self.word_length != WordLength::DataBits9 {
1371 return Err(DmaTransferFailure {
1372 error: DmaTransferError::InvalidWordLength,
1373 peripheral: self,
1374 channel,
1375 buffer,
1376 });
1377 }
1378
1379 let (source, words) = unsafe { buffer.read_buffer() };
1380 let values = unsafe { core::slice::from_raw_parts(source, words) };
1381 if values.iter().any(|word| *word > 0x01ff) {
1382 return Err(DmaTransferFailure {
1383 error: DmaTransferError::WordOutOfRange,
1384 peripheral: self,
1385 channel,
1386 buffer,
1387 });
1388 }
1389
1390 match dma_write_start::<UART, CHANNEL>(
1391 &mut channel,
1392 source.cast(),
1393 words.saturating_mul(2),
1394 1,
1395 ) {
1396 Ok(request_was_enabled) => Ok(TxDmaTransfer {
1397 tx: Some(self),
1398 channel: Some(channel),
1399 buffer: Some(buffer),
1400 request_was_enabled,
1401 }),
1402 Err(error) => Err(DmaTransferFailure {
1403 error,
1404 peripheral: self,
1405 channel,
1406 buffer,
1407 }),
1408 }
1409 }
1410
1411 pub fn blocking_write_dma<CHANNEL: DmaChannelId>(
1421 &mut self,
1422 channel: &mut DmaChannel<CHANNEL>,
1423 buffer: &[u8],
1424 timeout: u32,
1425 ) -> Result<(), DmaTransferError> {
1426 if self.word_length == WordLength::DataBits9 {
1427 return Err(DmaTransferError::InvalidWordLength);
1428 }
1429 dma_write::<UART, CHANNEL>(channel, buffer.as_ptr(), buffer.len(), 0, timeout)
1430 }
1431
1432 pub fn blocking_write_dma_9bit<CHANNEL: DmaChannelId>(
1436 &mut self,
1437 channel: &mut DmaChannel<CHANNEL>,
1438 buffer: &[u16],
1439 timeout: u32,
1440 ) -> Result<(), DmaTransferError> {
1441 if self.word_length != WordLength::DataBits9 {
1442 return Err(DmaTransferError::InvalidWordLength);
1443 }
1444 if buffer.iter().any(|word| *word > 0x01ff) {
1445 return Err(DmaTransferError::WordOutOfRange);
1446 }
1447 dma_write::<UART, CHANNEL>(
1448 channel,
1449 buffer.as_ptr().cast(),
1450 buffer.len().saturating_mul(2),
1451 1,
1452 timeout,
1453 )
1454 }
1455}
1456
1457impl<UART: Instance, TXPIN> Tx<UART, TXPIN, Owned> {
1458 pub fn reunite<RXPIN>(self, rx: Rx<UART, RXPIN, Borrowed>) -> Serial<UART, TXPIN, RXPIN>
1459 where
1460 TXPIN: TxPin<UART>,
1461 RXPIN: RxPin<UART>,
1462 {
1463 Serial::reunite(self, rx)
1464 }
1465
1466 pub fn release(self) -> (UART, TXPIN) {
1467 regs::<UART>().control1().modify(|_, w| w.ue().disable());
1468 (
1469 self.uart.expect("owned USART Tx missing USART owner"),
1470 self.pin,
1471 )
1472 }
1473}
1474
1475impl<UART: Instance, RXPIN, OWNER> ErrorType for Rx<UART, RXPIN, OWNER> {
1476 type Error = ErrorKind;
1477}
1478
1479impl<UART: Instance, RXPIN, OWNER> Rx<UART, RXPIN, OWNER> {
1480 pub fn is_idle(&self) -> bool {
1481 regs::<UART>().flags().read().idle().bit_is_set()
1482 }
1483
1484 pub fn clear_idle(&mut self) {
1485 regs::<UART>()
1486 .flags()
1487 .write(|w| w.idle().clear_bit_by_one());
1488 }
1489
1490 pub fn break_detected(&self) -> bool {
1491 regs::<UART>().flags().read().lbdf().bit_is_set()
1492 }
1493
1494 pub fn clear_break_detected(&mut self) {
1495 regs::<UART>()
1496 .flags()
1497 .write(|w| w.lbdf().clear_bit_by_one());
1498 }
1499
1500 pub fn read_dma<CHANNEL: DmaChannelId, BUFFER>(
1516 self,
1517 mut channel: DmaChannel<CHANNEL>,
1518 mut buffer: BUFFER,
1519 ) -> Result<
1520 RxDmaTransfer<UART, RXPIN, OWNER, CHANNEL, BUFFER>,
1521 DmaTransferFailure<Self, DmaChannel<CHANNEL>, BUFFER>,
1522 >
1523 where
1524 BUFFER: WriteBuffer<Word = u8>,
1525 {
1526 if self.word_length == WordLength::DataBits9 {
1527 return Err(DmaTransferFailure {
1528 error: DmaTransferError::InvalidWordLength,
1529 peripheral: self,
1530 channel,
1531 buffer,
1532 });
1533 }
1534
1535 let (destination, length) = unsafe { buffer.write_buffer() };
1536 match dma_read_start::<UART, CHANNEL>(&mut channel, destination, length, 0) {
1537 Ok(request_was_enabled) => Ok(RxDmaTransfer {
1538 rx: Some(self),
1539 channel: Some(channel),
1540 buffer: Some(buffer),
1541 request_was_enabled,
1542 }),
1543 Err(error) => Err(DmaTransferFailure {
1544 error,
1545 peripheral: self,
1546 channel,
1547 buffer,
1548 }),
1549 }
1550 }
1551
1552 pub fn read_dma_9bit<CHANNEL: DmaChannelId, BUFFER>(
1561 self,
1562 mut channel: DmaChannel<CHANNEL>,
1563 mut buffer: BUFFER,
1564 ) -> Result<
1565 RxDmaTransfer<UART, RXPIN, OWNER, CHANNEL, BUFFER>,
1566 DmaTransferFailure<Self, DmaChannel<CHANNEL>, BUFFER>,
1567 >
1568 where
1569 BUFFER: WriteBuffer<Word = u16>,
1570 {
1571 if self.word_length != WordLength::DataBits9 {
1572 return Err(DmaTransferFailure {
1573 error: DmaTransferError::InvalidWordLength,
1574 peripheral: self,
1575 channel,
1576 buffer,
1577 });
1578 }
1579
1580 let (destination, words) = unsafe { buffer.write_buffer() };
1581 match dma_read_start::<UART, CHANNEL>(
1582 &mut channel,
1583 destination.cast(),
1584 words.saturating_mul(2),
1585 1,
1586 ) {
1587 Ok(request_was_enabled) => Ok(RxDmaTransfer {
1588 rx: Some(self),
1589 channel: Some(channel),
1590 buffer: Some(buffer),
1591 request_was_enabled,
1592 }),
1593 Err(error) => Err(DmaTransferFailure {
1594 error,
1595 peripheral: self,
1596 channel,
1597 buffer,
1598 }),
1599 }
1600 }
1601
1602 pub fn blocking_read_dma<CHANNEL: DmaChannelId>(
1608 &mut self,
1609 channel: &mut DmaChannel<CHANNEL>,
1610 buffer: &mut [u8],
1611 timeout: u32,
1612 ) -> Result<(), DmaTransferError> {
1613 if self.word_length == WordLength::DataBits9 {
1614 return Err(DmaTransferError::InvalidWordLength);
1615 }
1616 dma_read::<UART, CHANNEL>(channel, buffer.as_mut_ptr(), buffer.len(), 0, timeout)
1617 }
1618
1619 pub fn blocking_read_dma_9bit<CHANNEL: DmaChannelId>(
1623 &mut self,
1624 channel: &mut DmaChannel<CHANNEL>,
1625 buffer: &mut [u16],
1626 timeout: u32,
1627 ) -> Result<(), DmaTransferError> {
1628 if self.word_length != WordLength::DataBits9 {
1629 return Err(DmaTransferError::InvalidWordLength);
1630 }
1631 dma_read::<UART, CHANNEL>(
1632 channel,
1633 buffer.as_mut_ptr().cast(),
1634 buffer.len().saturating_mul(2),
1635 1,
1636 timeout,
1637 )
1638 }
1639}
1640
1641impl<UART: Instance, RXPIN> Rx<UART, RXPIN, Owned> {
1642 pub fn release(self) -> (UART, RXPIN) {
1643 regs::<UART>().control1().modify(|_, w| w.ue().disable());
1644 (
1645 self.uart.expect("owned USART Rx missing USART owner"),
1646 self.pin,
1647 )
1648 }
1649}
1650
1651impl<UART: Instance, TXPIN, OWNER, CHANNEL: DmaChannelId, BUFFER>
1652 TxDmaTransfer<UART, TXPIN, OWNER, CHANNEL, BUFFER>
1653{
1654 pub fn is_done(&mut self) -> Result<bool, DmaTransferError> {
1655 self.channel
1656 .as_mut()
1657 .expect("DMA transfer channel missing")
1658 .poll()
1659 .map_err(Into::into)
1660 }
1661
1662 pub fn wait(
1663 mut self,
1664 ) -> Result<
1665 (Tx<UART, TXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER),
1666 DmaTransferFailure<Tx<UART, TXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER>,
1667 > {
1668 loop {
1669 match self.is_done() {
1670 Ok(true) => return Ok(self.take_parts()),
1671 Ok(false) => core::hint::spin_loop(),
1672 Err(error) => return Err(self.take_failure(error)),
1673 }
1674 }
1675 }
1676
1677 pub fn wait_timeout(
1678 mut self,
1679 timeout: u32,
1680 ) -> Result<
1681 (Tx<UART, TXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER),
1682 DmaTransferFailure<Tx<UART, TXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER>,
1683 > {
1684 for _ in 0..timeout {
1685 match self.is_done() {
1686 Ok(true) => return Ok(self.take_parts()),
1687 Ok(false) => core::hint::spin_loop(),
1688 Err(error) => return Err(self.take_failure(error)),
1689 }
1690 }
1691 Err(self.take_failure(DmaTransferError::Dma(DmaError::Timeout)))
1692 }
1693
1694 pub fn abort(mut self) -> (Tx<UART, TXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER) {
1695 self.take_parts()
1696 }
1697
1698 fn stop_and_restore(&mut self) {
1699 if let Some(channel) = self.channel.as_mut() {
1700 channel.stop();
1701 }
1702 regs::<UART>()
1703 .control3()
1704 .modify(|_, w| w.dmat().bit(self.request_was_enabled));
1705 }
1706
1707 fn take_parts(&mut self) -> (Tx<UART, TXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER) {
1708 self.stop_and_restore();
1709 (
1710 self.tx.take().expect("DMA transfer USART missing"),
1711 self.channel.take().expect("DMA transfer channel missing"),
1712 self.buffer.take().expect("DMA transfer buffer missing"),
1713 )
1714 }
1715
1716 fn take_failure(
1717 &mut self,
1718 error: DmaTransferError,
1719 ) -> DmaTransferFailure<Tx<UART, TXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER> {
1720 let (peripheral, channel, buffer) = self.take_parts();
1721 DmaTransferFailure {
1722 error,
1723 peripheral,
1724 channel,
1725 buffer,
1726 }
1727 }
1728}
1729
1730impl<UART: Instance, TXPIN, OWNER, CHANNEL: DmaChannelId, BUFFER> Drop
1731 for TxDmaTransfer<UART, TXPIN, OWNER, CHANNEL, BUFFER>
1732{
1733 fn drop(&mut self) {
1734 self.stop_and_restore();
1735 }
1736}
1737
1738impl<UART: Instance, RXPIN, OWNER, CHANNEL: DmaChannelId, BUFFER>
1739 RxDmaTransfer<UART, RXPIN, OWNER, CHANNEL, BUFFER>
1740{
1741 pub fn is_done(&mut self) -> Result<bool, DmaTransferError> {
1742 self.channel
1743 .as_mut()
1744 .expect("DMA transfer channel missing")
1745 .poll()
1746 .map_err(Into::into)
1747 }
1748
1749 pub fn wait(
1750 mut self,
1751 ) -> Result<
1752 (Rx<UART, RXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER),
1753 DmaTransferFailure<Rx<UART, RXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER>,
1754 > {
1755 loop {
1756 match self.is_done() {
1757 Ok(true) => return Ok(self.take_parts()),
1758 Ok(false) => core::hint::spin_loop(),
1759 Err(error) => return Err(self.take_failure(error)),
1760 }
1761 }
1762 }
1763
1764 pub fn wait_timeout(
1765 mut self,
1766 timeout: u32,
1767 ) -> Result<
1768 (Rx<UART, RXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER),
1769 DmaTransferFailure<Rx<UART, RXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER>,
1770 > {
1771 for _ in 0..timeout {
1772 match self.is_done() {
1773 Ok(true) => return Ok(self.take_parts()),
1774 Ok(false) => core::hint::spin_loop(),
1775 Err(error) => return Err(self.take_failure(error)),
1776 }
1777 }
1778 Err(self.take_failure(DmaTransferError::Dma(DmaError::Timeout)))
1779 }
1780
1781 pub fn abort(mut self) -> (Rx<UART, RXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER) {
1782 self.take_parts()
1783 }
1784
1785 fn stop_and_restore(&mut self) {
1786 if let Some(channel) = self.channel.as_mut() {
1787 channel.stop();
1788 }
1789 regs::<UART>()
1790 .control3()
1791 .modify(|_, w| w.dmar().bit(self.request_was_enabled));
1792 }
1793
1794 fn take_parts(&mut self) -> (Rx<UART, RXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER) {
1795 self.stop_and_restore();
1796 (
1797 self.rx.take().expect("DMA transfer USART missing"),
1798 self.channel.take().expect("DMA transfer channel missing"),
1799 self.buffer.take().expect("DMA transfer buffer missing"),
1800 )
1801 }
1802
1803 fn take_failure(
1804 &mut self,
1805 error: DmaTransferError,
1806 ) -> DmaTransferFailure<Rx<UART, RXPIN, OWNER>, DmaChannel<CHANNEL>, BUFFER> {
1807 let (peripheral, channel, buffer) = self.take_parts();
1808 DmaTransferFailure {
1809 error,
1810 peripheral,
1811 channel,
1812 buffer,
1813 }
1814 }
1815}
1816
1817impl<UART: Instance, RXPIN, OWNER, CHANNEL: DmaChannelId, BUFFER> Drop
1818 for RxDmaTransfer<UART, RXPIN, OWNER, CHANNEL, BUFFER>
1819{
1820 fn drop(&mut self) {
1821 self.stop_and_restore();
1822 }
1823}
1824
1825impl<UART, PIN> ErrorType for HalfDuplex<UART, PIN>
1826where
1827 UART: Instance,
1828 PIN: HalfDuplexPin<UART>,
1829{
1830 type Error = ErrorKind;
1831}
1832
1833impl<UART, PIN> Write for HalfDuplex<UART, PIN>
1834where
1835 UART: Instance,
1836 PIN: HalfDuplexPin<UART>,
1837{
1838 fn write(&mut self, byte: u8) -> NbResult<(), Self::Error> {
1839 if self.word_length == WordLength::DataBits9 {
1840 return Err(NbError::Other(ErrorKind::Other));
1841 }
1842 write_word::<UART>(u16::from(byte))
1843 }
1844
1845 fn flush(&mut self) -> NbResult<(), Self::Error> {
1846 flush::<UART>()
1847 }
1848}
1849
1850impl<UART, PIN> Write<u16> for HalfDuplex<UART, PIN>
1851where
1852 UART: Instance,
1853 PIN: HalfDuplexPin<UART>,
1854{
1855 fn write(&mut self, word: u16) -> NbResult<(), Self::Error> {
1856 if self.word_length != WordLength::DataBits9 || word > 0x01ff {
1857 return Err(NbError::Other(ErrorKind::Other));
1858 }
1859 write_word::<UART>(word)
1860 }
1861
1862 fn flush(&mut self) -> NbResult<(), Self::Error> {
1863 flush::<UART>()
1864 }
1865}
1866
1867impl<UART, PIN> Read for HalfDuplex<UART, PIN>
1868where
1869 UART: Instance,
1870 PIN: HalfDuplexPin<UART>,
1871{
1872 fn read(&mut self) -> NbResult<u8, Self::Error> {
1873 if self.word_length == WordLength::DataBits9 {
1874 return Err(NbError::Other(ErrorKind::Other));
1875 }
1876 read_word::<UART>().map(|word| word as u8)
1877 }
1878}
1879
1880impl<UART, PIN> Read<u16> for HalfDuplex<UART, PIN>
1881where
1882 UART: Instance,
1883 PIN: HalfDuplexPin<UART>,
1884{
1885 fn read(&mut self) -> NbResult<u16, Self::Error> {
1886 if self.word_length != WordLength::DataBits9 {
1887 return Err(NbError::Other(ErrorKind::Other));
1888 }
1889 read_word::<UART>()
1890 }
1891}
1892
1893impl<UART: Instance, TXPIN, OWNER> Write for Tx<UART, TXPIN, OWNER> {
1894 fn write(&mut self, byte: u8) -> NbResult<(), Self::Error> {
1895 if self.word_length == WordLength::DataBits9 {
1896 return Err(NbError::Other(ErrorKind::Other));
1897 }
1898 write_word::<UART>(u16::from(byte))
1899 }
1900
1901 fn flush(&mut self) -> NbResult<(), Self::Error> {
1902 flush::<UART>()
1903 }
1904}
1905
1906impl<UART: Instance, TXPIN, OWNER> Write<u16> for Tx<UART, TXPIN, OWNER> {
1907 fn write(&mut self, word: u16) -> NbResult<(), Self::Error> {
1908 if self.word_length != WordLength::DataBits9 || word > 0x01ff {
1909 return Err(NbError::Other(ErrorKind::Other));
1910 }
1911 write_word::<UART>(word)
1912 }
1913
1914 fn flush(&mut self) -> NbResult<(), Self::Error> {
1915 flush::<UART>()
1916 }
1917}
1918
1919impl<UART: Instance, TXPIN, OWNER> fmt::Write for Tx<UART, TXPIN, OWNER> {
1920 fn write_str(&mut self, s: &str) -> fmt::Result {
1921 for byte in s.bytes() {
1922 nb_block(|| self.write(byte)).map_err(|_| fmt::Error)?;
1923 }
1924
1925 nb_block(|| <Self as Write<u8>>::flush(self)).map_err(|_| fmt::Error)
1926 }
1927}
1928
1929impl<UART: Instance, RXPIN, OWNER> Read for Rx<UART, RXPIN, OWNER> {
1930 fn read(&mut self) -> NbResult<u8, Self::Error> {
1931 if self.word_length == WordLength::DataBits9 {
1932 return Err(NbError::Other(ErrorKind::Other));
1933 }
1934 read_word::<UART>().map(|word| word as u8)
1935 }
1936}
1937
1938impl<UART: Instance, RXPIN, OWNER> Read<u16> for Rx<UART, RXPIN, OWNER> {
1939 fn read(&mut self) -> NbResult<u16, Self::Error> {
1940 if self.word_length != WordLength::DataBits9 {
1941 return Err(NbError::Other(ErrorKind::Other));
1942 }
1943 read_word::<UART>()
1944 }
1945}
1946
1947fn dma_write_start<UART: Instance, CHANNEL: DmaChannelId>(
1948 channel: &mut DmaChannel<CHANNEL>,
1949 source: *const u8,
1950 length: usize,
1951 size: u32,
1952) -> Result<bool, DmaTransferError> {
1953 let regs = regs::<UART>();
1954 let destination = core::ptr::from_ref(regs.txdata()).cast_mut().cast::<u8>();
1955 let request_was_enabled = regs.control3().read().dmat().bit_is_set();
1956 regs.control3().modify(|_, w| w.dmat().enable());
1957
1958 if let Err(error) = channel.start(source, destination, length, dma_tx_config::<UART>(size)) {
1959 regs.control3()
1960 .modify(|_, w| w.dmat().bit(request_was_enabled));
1961 return Err(error.into());
1962 }
1963 Ok(request_was_enabled)
1964}
1965
1966fn dma_read_start<UART: Instance, CHANNEL: DmaChannelId>(
1967 channel: &mut DmaChannel<CHANNEL>,
1968 destination: *mut u8,
1969 length: usize,
1970 size: u32,
1971) -> Result<bool, DmaTransferError> {
1972 let regs = regs::<UART>();
1973 let source = core::ptr::from_ref(regs.rxdata()).cast::<u8>();
1974 let request_was_enabled = regs.control3().read().dmar().bit_is_set();
1975 regs.control3().modify(|_, w| w.dmar().enable());
1976
1977 if let Err(error) = channel.start(source, destination, length, dma_rx_config::<UART>(size)) {
1978 regs.control3()
1979 .modify(|_, w| w.dmar().bit(request_was_enabled));
1980 return Err(error.into());
1981 }
1982 Ok(request_was_enabled)
1983}
1984
1985fn dma_tx_config<UART: Instance>(size: u32) -> u32 {
1986 (1 << 3) | (1 << 5) | (size << 7) | (size << 9) | (UART::DMA_REQUEST << 21) | (1 << 26)
1987}
1988
1989fn dma_rx_config<UART: Instance>(size: u32) -> u32 {
1990 (1 << 4) | (1 << 6) | (size << 7) | (size << 9) | (UART::DMA_REQUEST << 17) | (1 << 25)
1991}
1992
1993fn dma_write<UART: Instance, CHANNEL: DmaChannelId>(
1994 channel: &mut DmaChannel<CHANNEL>,
1995 source: *const u8,
1996 length: usize,
1997 size: u32,
1998 timeout: u32,
1999) -> Result<(), DmaTransferError> {
2000 let regs = regs::<UART>();
2001 let destination = core::ptr::from_ref(regs.txdata()).cast_mut().cast::<u8>();
2002 let config = dma_tx_config::<UART>(size);
2003
2004 let request_was_enabled = regs.control3().read().dmat().bit_is_set();
2005 regs.control3().modify(|_, w| w.dmat().enable());
2006 let result = channel.transfer(source, destination, length, config, timeout);
2007 regs.control3()
2008 .modify(|_, w| w.dmat().bit(request_was_enabled));
2009 result.map_err(Into::into)
2010}
2011
2012fn dma_read<UART: Instance, CHANNEL: DmaChannelId>(
2013 channel: &mut DmaChannel<CHANNEL>,
2014 destination: *mut u8,
2015 length: usize,
2016 size: u32,
2017 timeout: u32,
2018) -> Result<(), DmaTransferError> {
2019 let regs = regs::<UART>();
2020 let source = core::ptr::from_ref(regs.rxdata()).cast::<u8>();
2021 let config = dma_rx_config::<UART>(size);
2022
2023 let request_was_enabled = regs.control3().read().dmar().bit_is_set();
2024 regs.control3().modify(|_, w| w.dmar().enable());
2025 let result = channel.transfer(source, destination, length, config, timeout);
2026 regs.control3()
2027 .modify(|_, w| w.dmar().bit(request_was_enabled));
2028 result.map_err(Into::into)
2029}
2030
2031fn write_word<UART: Instance>(word: u16) -> NbResult<(), ErrorKind> {
2032 let regs = regs::<UART>();
2033 if regs.flags().read().txe().bit_is_clear() {
2034 return Err(NbError::WouldBlock);
2035 }
2036 regs.txdata().write(|w| unsafe { w.tdr().bits(word) });
2037 Ok(())
2038}
2039
2040fn flush<UART: Instance>() -> NbResult<(), ErrorKind> {
2041 if regs::<UART>().flags().read().tc().bit_is_clear() {
2042 return Err(NbError::WouldBlock);
2043 }
2044 Ok(())
2045}
2046
2047fn read_word<UART: Instance>() -> NbResult<u16, ErrorKind> {
2048 let regs = regs::<UART>();
2049 let flags = regs.flags().read();
2050
2051 if flags.pe().bit_is_set() {
2052 regs.flags().write(|w| w.pe().clear_bit_by_one());
2053 return Err(NbError::Other(ErrorKind::Parity));
2054 }
2055 if flags.fe().bit_is_set() {
2056 regs.flags().write(|w| w.fe().clear_bit_by_one());
2057 return Err(NbError::Other(ErrorKind::FrameFormat));
2058 }
2059 if flags.nf().bit_is_set() {
2060 regs.flags().write(|w| w.nf().clear_bit_by_one());
2061 return Err(NbError::Other(ErrorKind::Noise));
2062 }
2063 if flags.ore().bit_is_set() {
2064 regs.flags().write(|w| w.ore().clear_bit_by_one());
2065 return Err(NbError::Other(ErrorKind::Overrun));
2066 }
2067 if flags.rxne().bit_is_clear() {
2068 return Err(NbError::WouldBlock);
2069 }
2070
2071 Ok(regs.rxdata().read().rdr().bits())
2072}
2073
2074#[inline(always)]
2075fn regs<UART: Instance>() -> &'static RegisterBlock {
2076 unsafe { &*UART::ptr() }
2077}
2078
2079#[inline(always)]
2080fn calc_baudrate_divisor(baudrate: u32) -> Result<u16, ConfigError> {
2081 if baudrate == 0 {
2082 return Err(ConfigError::ZeroBaudrate);
2083 }
2084
2085 let sys_clock: u32 = system_clock().into();
2086 let p = unsafe { Peripherals::steal() };
2087 let ahb_divisor = p.pm.div_ahb().read().bits().saturating_add(1);
2088 let apb_p_divisor = p.pm.div_apb_p().read().bits().saturating_add(1);
2089 let clock = sys_clock / ahb_divisor / apb_p_divisor;
2090 let divisor = (u64::from(clock) + u64::from(baudrate) / 2) / u64::from(baudrate);
2091
2092 if divisor < 16 {
2093 return Err(ConfigError::BaudrateTooHigh);
2094 }
2095 if divisor > u64::from(u16::MAX) {
2096 return Err(ConfigError::BaudrateTooLow);
2097 }
2098
2099 Ok(divisor as u16)
2100}
2101
2102fn nb_block<T, E>(mut f: impl FnMut() -> NbResult<T, E>) -> Result<T, E> {
2103 loop {
2104 match f() {
2105 Ok(value) => return Ok(value),
2106 Err(NbError::WouldBlock) => core::hint::spin_loop(),
2107 Err(NbError::Other(error)) => return Err(error),
2108 }
2109 }
2110}