Skip to main content

ch32_hal/usart/
mod.rs

1//! USART - Universal Synchronous Asynchronous Receiver Transmitter
2
3/*
4Full-duplex or half-duplex synchronous or asynchronous communication
5NRZ data format
6Fractional baud rate generator
7Programmable data length
8Configurable stop bits
9Supports LIN, IrDA encoder, smart card
10Supports DMA
11Multiple interrupt sources
12 */
13
14use core::future::poll_fn;
15use core::marker::PhantomData;
16use core::sync::atomic::{compiler_fence, AtomicU32, Ordering};
17#[cfg(usart_v4x7)]
18use core::sync::atomic::AtomicUsize;
19use core::task::Poll;
20
21use embassy_sync::waitqueue::AtomicWaker;
22use futures::future::{select, Either};
23
24use crate::dma::ChannelAndRequest;
25use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin, Speed};
26use crate::internal::drop::OnDrop;
27use crate::interrupt::typelevel::Interrupt;
28use crate::mode::{Async, Blocking, Mode};
29use crate::time::Hertz;
30use crate::{interrupt, pac, peripherals, Peri};
31
32mod ringbuffered;
33pub use ringbuffered::RingBufferedUartRx;
34
35/// Interrupt handler.
36pub struct InterruptHandler<T: Instance> {
37    _phantom: PhantomData<T>,
38}
39
40impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
41    unsafe fn on_interrupt() {
42        let r = T::regs();
43        let s = T::state();
44
45        let (sr, cr1, cr3) = (r.statr().read(), r.ctlr1().read(), r.ctlr3().read());
46
47        let has_errors = (sr.pe() && cr1.peie()) || ((sr.fe() || sr.ne() || sr.ore()) && cr3.eie());
48        if has_errors {
49            // Latch the receive error bits: this `STATR` read plus the DMA's
50            // `DATAR` read can clear them before the reader gets to poll, and
51            // the reader would then wait forever for a transfer that the
52            // disabled DMA request can no longer complete.
53            critical_section::with(|_| {
54                // PE/FE/NE/ORE are `STATR` bits 0..=3.
55                let error_bits = sr.0 & 0xf;
56                let latched = s.rx_errors.load(Ordering::Relaxed);
57                s.rx_errors.store(latched | error_bits, Ordering::Release);
58            });
59
60            // clear all interrupts and DMA Rx Request
61            r.ctlr1().modify(|w| {
62                // disable RXNE interrupt
63                w.set_rxneie(false);
64                // disable parity interrupt
65                w.set_peie(false);
66                // disable idle line interrupt
67                w.set_idleie(false);
68            });
69            r.ctlr3().modify(|w| {
70                // disable Error Interrupt: (Frame error, Noise error, Overrun error)
71                w.set_eie(false);
72                // disable DMA Rx Request
73                w.set_dmar(false);
74            });
75        } else if cr1.idleie() && sr.idle() {
76            // IDLE detected: no more data will come. Keep DMAR set: a
77            // one-shot read stops the DMA itself once it sees this flag, and
78            // the ring-buffered receiver must keep receiving across idle
79            // gaps, because an idle bus is not the end of the stream.
80            r.ctlr1().modify(|w| {
81                // disable idle line detection
82                w.set_idleie(false);
83            });
84        } else if cr1.tcie() && sr.tc() {
85            // Transmission complete detected
86            r.ctlr1().modify(|w| {
87                // disable Transmission complete interrupt
88                w.set_tcie(false);
89            });
90        } else if cr1.rxneie() {
91            // We cannot check the RXNE flag as it is auto-cleared by the DMA controller
92
93            // It is up to the listener to determine if this in fact was a RX event and disable the RXNE detection
94        } else {
95            return;
96        }
97
98        compiler_fence(Ordering::SeqCst);
99        s.rx_waker.wake();
100        s.tx_waker.wake();
101    }
102}
103
104#[derive(Clone, Copy, PartialEq, Eq, Debug)]
105#[cfg_attr(feature = "defmt", derive(defmt::Format))]
106pub enum DataBits {
107    DataBits8 = 0,
108    DataBits9 = 1,
109}
110
111#[derive(Clone, Copy, PartialEq, Eq, Debug)]
112#[cfg_attr(feature = "defmt", derive(defmt::Format))]
113pub enum Parity {
114    ParityNone,
115    ParityEven,
116    ParityOdd,
117}
118
119#[derive(Clone, Copy, PartialEq, Eq, Debug)]
120#[cfg_attr(feature = "defmt", derive(defmt::Format))]
121pub enum StopBits {
122    #[doc = "1 stop bit"]
123    STOP1 = 0,
124    #[doc = "0.5 stop bits"]
125    STOP0P5 = 0b01,
126    #[doc = "2 stop bits"]
127    STOP2 = 0b10,
128    #[doc = "1.5 stop bits"]
129    STOP1P5 = 0b11,
130}
131
132#[non_exhaustive]
133#[derive(Clone, Copy, PartialEq, Eq, Debug)]
134pub struct Config {
135    pub baudrate: u32,
136    pub data_bits: DataBits,
137    pub stop_bits: StopBits,
138    pub parity: Parity,
139
140    /// If true: on a read-like method, if there is a latent error pending,
141    /// the read will abort and the error will be reported and cleared
142    ///
143    /// If false: the error is ignored and cleared
144    pub detect_previous_overrun: bool,
145
146    half_duplex: bool,
147}
148impl Default for Config {
149    /// 115200 8N1
150    fn default() -> Self {
151        Self {
152            baudrate: 115200,
153            data_bits: DataBits::DataBits8,
154            stop_bits: StopBits::STOP1,
155            parity: Parity::ParityNone,
156
157            detect_previous_overrun: false,
158
159            half_duplex: false,
160        }
161    }
162}
163
164#[derive(Debug, Eq, PartialEq, Copy, Clone)]
165#[cfg_attr(feature = "defmt", derive(defmt::Format))]
166#[non_exhaustive]
167pub enum Error {
168    /// Framing error
169    // FE
170    Framing,
171    /// Noise error
172    // NE
173    Noise,
174    /// RX buffer overrun
175    // ORE
176    Overrun,
177    /// Parity check error
178    // PE
179    Parity,
180    /// Buffer too large for DMA
181    BufferTooLong,
182}
183
184#[derive(Clone, Copy, PartialEq, Eq, Debug)]
185#[cfg_attr(feature = "defmt", derive(defmt::Format))]
186pub enum ConfigError {
187    BaudrateTooLow,
188    BaudrateTooHigh,
189}
190
191enum ReadCompletionEvent {
192    // DMA Read transfer completed first
193    DmaCompleted,
194    // Idle line detected first
195    Idle(usize),
196}
197
198// ========
199// ## Tx Part
200
201/// Tx-only UART Driver.
202pub struct UartTx<'d, T: Instance, M: Mode> {
203    _phantom: PhantomData<(T, M)>,
204    tx: Option<Peri<'d, AnyPin>>,
205    cts: Option<Peri<'d, AnyPin>>,
206    tx_dma: Option<ChannelAndRequest<'d>>,
207}
208
209impl<'d, T: Instance, M: Mode> UartTx<'d, T, M> {
210    /// Reconfigure the driver
211    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
212        reconfigure::<T>(config)
213    }
214
215    fn new_inner(
216        _peri: Peri<'d, T>,
217        tx: Option<Peri<'d, AnyPin>>,
218        cts: Option<Peri<'d, AnyPin>>,
219        tx_dma: Option<ChannelAndRequest<'d>>,
220        config: Config,
221    ) -> Result<Self, ConfigError> {
222        enable_peripheral::<T>();
223        let cleanup = OnDrop::new(|| {
224            tx.as_ref().map(|pin| pin.set_as_disconnected());
225            cts.as_ref().map(|pin| pin.set_as_disconnected());
226            disable_peripheral::<T>();
227        });
228
229        let rb = T::regs();
230        rb.ctlr3().modify(|w| w.set_ctse(cts.is_some()));
231        configure(&rb, &config, T::frequency(), true, false)?;
232
233        #[cfg(usart_v4x7)]
234        if tx_dma.is_some() {
235            T::Interrupt::unpend();
236            unsafe { T::Interrupt::enable() };
237        }
238
239        // create state once!
240        let _s = T::state();
241
242        cleanup.defuse();
243        Ok(Self {
244            _phantom: PhantomData,
245            tx,
246            cts,
247            tx_dma,
248        })
249    }
250
251    /// Perform a blocking UART write
252    pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
253        let rb = T::regs();
254
255        for &c in buffer {
256            while !rb.statr().read().tc() {} // wait tx complete
257            rb.datar().write(|w| w.set_dr(c as u16));
258        }
259        Ok(())
260    }
261
262    /// Block until transmission complete
263    pub fn blocking_flush(&mut self) -> Result<(), Error> {
264        let rb = T::regs();
265        if rb.ctlr1().read().te() {
266            while !rb.statr().read().tc() {} // wait for last bit on wire.
267        }
268        Ok(())
269    }
270}
271
272impl<'d, T: Instance> UartTx<'d, T, Async> {
273    /// Useful if you only want Uart Tx. It saves 1 pin and consumes a little less power.
274    #[cfg_attr(usart_v4x7, doc = "The interrupt binding is required for asynchronous flush completion.")]
275    pub fn new<#[cfg(not(afio_h4))] const REMAP: u8>(
276        peri: Peri<'d, T>,
277        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
278        #[cfg(usart_v4x7)] _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
279        tx_dma: Peri<'d, impl TxDma<T>>,
280        config: Config,
281    ) -> Result<Self, ConfigError> {
282        apply_remap!();
283        Self::new_inner(peri, new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)), None, new_dma!(tx_dma), config)
284    }
285
286    /// Create a new tx-only UART with a clear-to-send pin
287    #[cfg_attr(usart_v4x7, doc = "The interrupt binding is required for asynchronous flush completion.")]
288    pub fn new_with_cts<#[cfg(not(afio_h4))] const REMAP: u8>(
289        peri: Peri<'d, T>,
290        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
291        cts: Peri<'d, if_remap!(impl CtsPin<T, REMAP>)>,
292        #[cfg(usart_v4x7)] _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
293        tx_dma: Peri<'d, impl TxDma<T>>,
294        config: Config,
295    ) -> Result<Self, ConfigError> {
296        apply_remap!();
297        Self::new_inner(
298            peri,
299            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)),
300            new_pin!(cts, AfType::input(Pull::None)),
301            new_dma!(tx_dma),
302            config,
303        )
304    }
305
306    /// Initiate an asynchronous UART write
307    pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
308        if buffer.is_empty() {
309            return Ok(());
310        }
311        if buffer.len() > 0xffff {
312            return Err(Error::BufferTooLong);
313        }
314        let registers = T::regs();
315        let cleanup = OnDrop::new(move || registers.ctlr3().modify(|register| register.set_dmat(false)));
316        registers.statr().write(|register| {
317            register.0 = u32::from(u16::MAX);
318            register.set_tc(false);
319        });
320        let ch = self.tx_dma.as_mut().unwrap();
321        T::regs().ctlr3().modify(|reg| {
322            reg.set_dmat(true);
323        });
324        // If we don't assign future to a variable, the data register pointer
325        // is held across an await and makes the future non-Send.
326        let transfer = unsafe { ch.write(buffer, T::regs().datar().as_ptr() as _, Default::default()) };
327        transfer.await;
328        drop(cleanup);
329        Ok(())
330    }
331
332    /// Wait until transmission complete
333    pub async fn flush(&mut self) -> Result<(), Error> {
334        let r = T::regs();
335        let cleanup = OnDrop::new(move || r.ctlr1().modify(|register| register.set_tcie(false)));
336        if r.ctlr1().read().te() && !r.statr().read().tc() {
337            r.ctlr1().modify(|w| {
338                // enable Transmission Complete interrupt
339                w.set_tcie(true);
340            });
341
342            compiler_fence(Ordering::SeqCst);
343
344            // future which completes when Transmission complete is detected
345            let abort = poll_fn(move |cx| {
346                let s = T::state();
347                s.tx_waker.register(cx.waker());
348
349                let sr = r.statr().read();
350                if sr.tc() {
351                    // Transmission complete detected
352                    return Poll::Ready(());
353                }
354
355                Poll::Pending
356            });
357
358            abort.await;
359        }
360
361        drop(cleanup);
362
363        Ok(())
364    }
365}
366
367impl<'d, T: Instance> UartTx<'d, T, Blocking> {
368    /// Create a new blocking tx-only UART with no hardware flow control.
369    ///
370    /// Useful if you only want Uart Tx. It saves 1 pin and consumes a little less power.
371    pub fn new_blocking<#[cfg(not(afio_h4))] const REMAP: u8>(
372        peri: Peri<'d, T>,
373        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
374        config: Config,
375    ) -> Result<Self, ConfigError> {
376        apply_remap!();
377        Self::new_inner(peri, new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)), None, None, config)
378    }
379
380    /// Create a new blocking tx-only UART with a clear-to-send pin
381    pub fn new_blocking_with_cts<#[cfg(not(afio_h4))] const REMAP: u8>(
382        peri: Peri<'d, T>,
383        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
384        cts: Peri<'d, if_remap!(impl CtsPin<T, REMAP>)>,
385        config: Config,
386    ) -> Result<Self, ConfigError> {
387        apply_remap!();
388        Self::new_inner(peri, new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)), new_pin!(cts, AfType::input(Pull::None)), None, config)
389    }
390}
391
392// ========
393// ## Rx Part
394
395/// Rx-only UART Driver.
396pub struct UartRx<'d, T: Instance, M: Mode> {
397    _phantom: PhantomData<(T, M)>,
398    rx: Option<Peri<'d, AnyPin>>,
399    rts: Option<Peri<'d, AnyPin>>,
400    rx_dma: Option<ChannelAndRequest<'d>>,
401    detect_previous_overrun: bool,
402    buffered_sr: pac::usart::regs::Statr,
403}
404
405impl<'d, T: Instance, M: Mode> UartRx<'d, T, M> {
406    fn new_inner(
407        _peri: Peri<'d, T>,
408        rx: Option<Peri<'d, AnyPin>>,
409        rts: Option<Peri<'d, AnyPin>>,
410        rx_dma: Option<ChannelAndRequest<'d>>,
411        config: Config,
412    ) -> Result<Self, ConfigError> {
413        enable_peripheral::<T>();
414        let cleanup = OnDrop::new(|| {
415            rx.as_ref().map(|pin| pin.set_as_disconnected());
416            rts.as_ref().map(|pin| pin.set_as_disconnected());
417            disable_peripheral::<T>();
418        });
419
420        let r = T::regs();
421        r.ctlr3().write(|w| {
422            w.set_rtse(rts.is_some());
423        });
424        configure(&r, &config, T::frequency(), false, true)?;
425
426        T::Interrupt::unpend();
427        unsafe { T::Interrupt::enable() };
428
429        // create state once!
430        let _s = T::state();
431
432        cleanup.defuse();
433        Ok(Self {
434            _phantom: PhantomData,
435            rx,
436            rts,
437            rx_dma,
438            detect_previous_overrun: config.detect_previous_overrun,
439            buffered_sr: pac::usart::regs::Statr(0),
440        })
441    }
442
443    /// Reconfigure the driver
444    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
445        reconfigure::<T>(config)?;
446        self.detect_previous_overrun = config.detect_previous_overrun;
447        Ok(())
448    }
449
450    // The same as embassy-stm32's usart_v1
451    // checks rxne
452    fn check_rx_flags(&mut self) -> Result<bool, Error> {
453        let r = T::regs();
454        loop {
455            // Handle all buffered error flags.
456            if self.buffered_sr.pe() {
457                self.buffered_sr.set_pe(false);
458                return Err(Error::Parity);
459            } else if self.buffered_sr.fe() {
460                self.buffered_sr.set_fe(false);
461                return Err(Error::Framing);
462            } else if self.buffered_sr.ne() {
463                self.buffered_sr.set_ne(false);
464                return Err(Error::Noise);
465            } else if self.buffered_sr.ore() {
466                self.buffered_sr.set_ore(false);
467                return Err(Error::Overrun);
468            } else if self.buffered_sr.rxne() {
469                self.buffered_sr.set_rxne(false);
470                return Ok(true);
471            } else {
472                // No error flags from previous iterations were set: Check the actual status register
473                let sr = r.statr().read();
474                if !sr.rxne() {
475                    return Ok(false);
476                }
477
478                // Buffer the status register and let the loop handle the error flags.
479                self.buffered_sr = sr;
480            }
481        }
482    }
483
484    /// Read a single u8 if there is one available, otherwise return WouldBlock
485    #[allow(unused)]
486    pub fn nb_read(&mut self) -> Result<u8, nb::Error<Error>> {
487        let r = T::regs();
488        if self.check_rx_flags()? {
489            Ok(r.datar().read().dr() as u8)
490        } else {
491            Err(nb::Error::WouldBlock)
492        }
493    }
494
495    /// Perform a blocking read into `buffer`
496    pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
497        let r = T::regs();
498        for b in buffer {
499            while !self.check_rx_flags()? {}
500            *b = r.datar().read().dr() as u8
501        }
502        Ok(())
503    }
504}
505
506impl<'d, T: Instance> UartRx<'d, T, Async> {
507    /// Create a new rx-only UART with no hardware flow control.
508    ///
509    /// Useful if you only want Uart Rx. It saves 1 pin and consumes a little less power.
510    pub fn new<#[cfg(not(afio_h4))] const REMAP: u8>(
511        peri: Peri<'d, T>,
512        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
513        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
514        rx_dma: Peri<'d, impl RxDma<T>>,
515        config: Config,
516    ) -> Result<Self, ConfigError> {
517        apply_remap!();
518        Self::new_inner(peri, new_pin!(rx, AfType::input(Pull::None)), None, new_dma!(rx_dma), config)
519    }
520
521    /// Create a new rx-only UART with a request-to-send pin
522    pub fn new_with_rts<#[cfg(not(afio_h4))] const REMAP: u8>(
523        peri: Peri<'d, T>,
524        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
525        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
526        rts: Peri<'d, if_remap!(impl RtsPin<T, REMAP>)>,
527        rx_dma: Peri<'d, impl RxDma<T>>,
528        config: Config,
529    ) -> Result<Self, ConfigError> {
530        apply_remap!();
531        Self::new_inner(
532            peri,
533            new_pin!(rx, AfType::input(Pull::None)),
534            new_pin!(rts, AfType::output(OutputType::PushPull, Speed::High)),
535            new_dma!(rx_dma),
536            config,
537        )
538    }
539
540    /// Initiate an asynchronous UART read
541    pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
542        self.inner_read(buffer, false).await?;
543
544        Ok(())
545    }
546
547    /// Initiate an asynchronous read with idle line detection enabled
548    pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
549        self.inner_read(buffer, true).await
550    }
551
552    async fn inner_read_run(
553        &mut self,
554        buffer: &mut [u8],
555        enable_idle_line_detection: bool,
556    ) -> Result<ReadCompletionEvent, Error> {
557        let r = T::regs();
558
559        // make sure USART state is restored to neutral state when this future is dropped
560        let on_drop = OnDrop::new(move || {
561            // defmt::trace!("Clear all USART interrupts and DMA Read Request");
562            // clear all interrupts and DMA Rx Request
563            r.ctlr1().modify(|w| {
564                // disable RXNE interrupt
565                w.set_rxneie(false);
566                // disable parity interrupt
567                w.set_peie(false);
568                // disable idle line interrupt
569                w.set_idleie(false);
570            });
571            r.ctlr3().modify(|w| {
572                // disable Error Interrupt: (Frame error, Noise error, Overrun error)
573                w.set_eie(false);
574                // disable DMA Rx Request
575                w.set_dmar(false);
576            });
577        });
578
579        let ch = self.rx_dma.as_mut().unwrap();
580
581        let buffer_len = buffer.len();
582
583        // Start USART DMA
584        // will not do anything yet because DMAR is not yet set
585        // future which will complete when DMA Read request completes
586        let transfer = unsafe { ch.read(T::regs().datar().as_ptr() as _, buffer, Default::default()) };
587
588        // clear ORE flag just before enabling DMA Rx Request: can be mandatory for the second transfer
589        let status = r.statr().read();
590        if self.detect_previous_overrun {
591            if let Some(error) = receive_error(status) {
592                let _ = r.datar().read();
593                return Err(error);
594            }
595        }
596        if !self.detect_previous_overrun || enable_idle_line_detection {
597            // This read also clears the error and idle interrupt flags on v1.
598            let _ = r.datar().read().dr();
599            // clear_interrupt_flags(r, sr);
600        }
601
602        // Start from a clean slate: errors latched before this transfer belong
603        // to an earlier read (or to a ring-buffered reception).
604        critical_section::with(|_| T::state().rx_errors.store(0, Ordering::Release));
605
606        r.ctlr1().modify(|w| {
607            // disable RXNE interrupt
608            w.set_rxneie(false);
609            // enable parity interrupt if not ParityNone
610            w.set_peie(w.pce());
611            w.set_idleie(enable_idle_line_detection);
612        });
613
614        r.ctlr3().modify(|w| {
615            // enable Error Interrupt: (Frame error, Noise error, Overrun error)
616            w.set_eie(true);
617            // enable DMA Rx Request
618            w.set_dmar(true);
619        });
620
621        compiler_fence(Ordering::SeqCst);
622
623        // In case of errors already pending when reception started, interrupts may have already been raised
624        // and lead to reception abortion (Overrun error for instance). In such a case, all interrupts
625        // have been disabled in interrupt handler and DMA Rx Request has been disabled.
626
627        compiler_fence(Ordering::SeqCst);
628
629        // future which completes when idle line or error is detected
630        let abort = poll_fn(move |cx| {
631            let s = T::state();
632
633            s.rx_waker.register(cx.waker());
634
635            compiler_fence(Ordering::SeqCst);
636
637            // This closure never reads `STATR`: a read here would arm
638            // the RM ยง17.10.1 "read STATR, then read DATAR" clear sequence, and
639            // the DMA's next `DATAR` read could clear a FE/NE/ORE before the
640            // handler sees it. The handler latches the errors, and acknowledges
641            // an idle line by clearing `IDLEIE`. Take both together, errors
642            // first, since the error path clears `IDLEIE` too.
643            let (latched, idle) = critical_section::with(|_| {
644                let latched = s.rx_errors.load(Ordering::Acquire);
645                s.rx_errors.store(0, Ordering::Release);
646                (latched, enable_idle_line_detection && !r.ctlr1().read().idleie())
647            });
648            if let Some(error) = receive_error(pac::usart::regs::Statr(latched)) {
649                r.ctlr3().modify(|register| register.set_dmar(false));
650                let _ = r.datar().read();
651                return Poll::Ready(Err(error));
652            }
653
654            if idle {
655                r.ctlr3().modify(|register| register.set_dmar(false));
656                let _ = r.datar().read();
657                // Idle line detected
658                return Poll::Ready(Ok(()));
659            }
660
661            Poll::Pending
662        });
663
664        // wait for the first of DMA request or idle line detected to completes
665        // select consumes its arguments
666        // when transfer is dropped, it will stop the DMA request
667        let r = match select(abort, transfer).await {
668            // DMA transfer completed first
669            Either::Right(((), _)) => Ok(ReadCompletionEvent::DmaCompleted),
670
671            // Idle line detected first
672            Either::Left((Ok(()), mut transfer)) => {
673                transfer.request_stop();
674                Ok(ReadCompletionEvent::Idle(buffer_len - transfer.get_remaining_transfers() as usize))
675            }
676
677            // error occurred
678            Either::Left((Err(e), _)) => Err(e),
679        };
680
681        drop(on_drop);
682
683        r
684    }
685
686    async fn inner_read(&mut self, buffer: &mut [u8], enable_idle_line_detection: bool) -> Result<usize, Error> {
687        if buffer.is_empty() {
688            return Ok(0);
689        } else if buffer.len() > 0xFFFF {
690            return Err(Error::BufferTooLong);
691        }
692
693        let buffer_len = buffer.len();
694
695        // wait for DMA to complete or IDLE line detection if requested
696        let res = self.inner_read_run(buffer, enable_idle_line_detection).await;
697
698        match res {
699            Ok(ReadCompletionEvent::DmaCompleted) => Ok(buffer_len),
700            Ok(ReadCompletionEvent::Idle(n)) => Ok(n),
701            Err(e) => Err(e),
702        }
703    }
704}
705
706impl<'d, T: Instance> UartRx<'d, T, Blocking> {
707    /// Create a new rx-only UART with no hardware flow control.
708    ///
709    /// Useful if you only want Uart Rx. It saves 1 pin and consumes a little less power.
710    pub fn new_blocking<#[cfg(not(afio_h4))] const REMAP: u8>(
711        peri: Peri<'d, T>,
712        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
713        config: Config,
714    ) -> Result<Self, ConfigError> {
715        apply_remap!();
716        Self::new_inner(peri, new_pin!(rx, AfType::input(Pull::None)), None, None, config)
717    }
718
719    /// Create a new rx-only UART with a request-to-send pin
720    pub fn new_blocking_with_rts<#[cfg(not(afio_h4))] const REMAP: u8>(
721        peri: Peri<'d, T>,
722        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
723        rts: Peri<'d, if_remap!(impl RtsPin<T, REMAP>)>,
724        config: Config,
725    ) -> Result<Self, ConfigError> {
726        apply_remap!();
727        Self::new_inner(peri, new_pin!(rx, AfType::input(Pull::None)), new_pin!(rts, AfType::output(OutputType::PushPull, Speed::High)), None, config)
728    }
729}
730
731// ========
732// ## Common part, Drop impl
733impl<'d, T: Instance, M: Mode> Drop for UartTx<'d, T, M> {
734    fn drop(&mut self) {
735        #[cfg(usart_v4x7)]
736        {
737            T::regs().ctlr1().modify(|register| {
738                register.set_te(false);
739                register.set_tcie(false);
740            });
741            T::regs().ctlr3().modify(|register| {
742                register.set_dmat(false);
743                register.set_ctse(false);
744            });
745        }
746        self.tx.as_ref().map(|x| x.set_as_disconnected());
747        self.cts.as_ref().map(|x| x.set_as_disconnected());
748        disable_peripheral::<T>();
749    }
750}
751
752impl<'d, T: Instance, M: Mode> Drop for UartRx<'d, T, M> {
753    fn drop(&mut self) {
754        #[cfg(usart_v4x7)]
755        {
756            T::regs().ctlr1().modify(|register| {
757                register.set_re(false);
758                register.set_rxneie(false);
759                register.set_peie(false);
760                register.set_idleie(false);
761            });
762            T::regs().ctlr3().modify(|register| {
763                register.set_dmar(false);
764                register.set_eie(false);
765                register.set_rtse(false);
766            });
767        }
768        self.rx.as_ref().map(|x| x.set_as_disconnected());
769        self.rts.as_ref().map(|x| x.set_as_disconnected());
770        disable_peripheral::<T>();
771    }
772}
773
774// ========
775// ## Bidirectional UART
776
777/// Bidirectional UART Driver, which acts as a combination of [`UartTx`] and [`UartRx`].
778///
779/// ### Notes on [`embedded_io::Read`]
780///
781/// `embedded_io::Read` requires guarantees that the base [`UartRx`] cannot provide.
782///
783/// See [`UartRx`] for more details, and see [`BufferedUart`] and [`RingBufferedUartRx`]
784/// as alternatives that do provide the necessary guarantees for `embedded_io::Read`.
785pub struct Uart<'d, T: Instance, M: Mode> {
786    tx: UartTx<'d, T, M>,
787    rx: UartRx<'d, T, M>,
788}
789
790impl<'d, T: Instance, M: Mode> Uart<'d, T, M> {
791    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
792        self.tx.set_config(config)?;
793        self.rx.set_config(config)
794    }
795
796    fn new_inner(
797        _peri: Peri<'d, T>,
798        rx: Option<Peri<'d, AnyPin>>,
799        tx: Option<Peri<'d, AnyPin>>,
800        rts: Option<Peri<'d, AnyPin>>,
801        cts: Option<Peri<'d, AnyPin>>,
802        tx_dma: Option<ChannelAndRequest<'d>>,
803        rx_dma: Option<ChannelAndRequest<'d>>,
804        config: Config,
805    ) -> Result<Self, ConfigError> {
806        // UartRx and UartTx have one refcount each.
807        enable_peripheral::<T>();
808        enable_peripheral::<T>();
809        let cleanup = OnDrop::new(|| {
810            rx.as_ref().map(|pin| pin.set_as_disconnected());
811            tx.as_ref().map(|pin| pin.set_as_disconnected());
812            rts.as_ref().map(|pin| pin.set_as_disconnected());
813            cts.as_ref().map(|pin| pin.set_as_disconnected());
814            disable_peripheral::<T>();
815            disable_peripheral::<T>();
816        });
817
818        let r = T::regs();
819
820        r.ctlr3().write(|w| {
821            w.set_rtse(rts.is_some());
822            w.set_ctse(cts.is_some());
823        });
824        configure(&r, &config, T::frequency(), true, true)?;
825
826        T::Interrupt::unpend();
827        unsafe { T::Interrupt::enable() };
828
829        // create state once!
830        let _s = T::state();
831
832        cleanup.defuse();
833        Ok(Self {
834            tx: UartTx {
835                _phantom: PhantomData,
836                tx,
837                cts,
838                tx_dma,
839            },
840            rx: UartRx {
841                _phantom: PhantomData,
842                rx,
843                rts,
844                rx_dma,
845                detect_previous_overrun: config.detect_previous_overrun,
846                buffered_sr: pac::usart::regs::Statr(0),
847            },
848        })
849    }
850
851    /// Perform a blocking write
852    pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
853        self.tx.blocking_write(buffer)
854    }
855
856    /// Block until transmission complete
857    pub fn blocking_flush(&mut self) -> Result<(), Error> {
858        self.tx.blocking_flush()
859    }
860
861    /// Read a single `u8` or return `WouldBlock`
862    #[allow(unused)]
863    pub(crate) fn nb_read(&mut self) -> Result<u8, nb::Error<Error>> {
864        self.rx.nb_read()
865    }
866
867    /// Perform a blocking read into `buffer`
868    pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
869        self.rx.blocking_read(buffer)
870    }
871
872    /// Split the Uart into a transmitter and receiver, which is
873    /// particularly useful when having two tasks correlating to
874    /// transmitting and receiving.
875    pub fn split(self) -> (UartTx<'d, T, M>, UartRx<'d, T, M>) {
876        (self.tx, self.rx)
877    }
878}
879
880impl<'d, T: Instance> Uart<'d, T, Async> {
881    /// Create a new bidirectional UARTUart
882    pub fn new<#[cfg(not(afio_h4))] const REMAP: u8>(
883        peri: Peri<'d, T>,
884        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
885        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
886        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
887        tx_dma: Peri<'d, impl TxDma<T>>,
888        rx_dma: Peri<'d, impl RxDma<T>>,
889        config: Config,
890    ) -> Result<Self, ConfigError> {
891        apply_remap!();
892        Self::new_inner(
893            peri,
894            new_pin!(rx, AfType::input(Pull::None)),
895            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)),
896            None,
897            None,
898            new_dma!(tx_dma),
899            new_dma!(rx_dma),
900            config,
901        )
902    }
903
904    /// Create a new bidirectional UART with request-to-send and clear-to-send pins
905    pub fn new_with_rtscts<#[cfg(not(afio_h4))] const REMAP: u8>(
906        peri: Peri<'d, T>,
907        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
908        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
909        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
910        rts: Peri<'d, if_remap!(impl RtsPin<T, REMAP>)>,
911        cts: Peri<'d, if_remap!(impl CtsPin<T, REMAP>)>,
912        tx_dma: Peri<'d, impl TxDma<T>>,
913        rx_dma: Peri<'d, impl RxDma<T>>,
914        config: Config,
915    ) -> Result<Self, ConfigError> {
916        apply_remap!();
917        Self::new_inner(
918            peri,
919            new_pin!(rx, AfType::input(Pull::None)),
920            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)),
921            new_pin!(rts, AfType::output(OutputType::PushPull, Speed::High)),
922            new_pin!(cts, AfType::input(Pull::None)),
923            new_dma!(tx_dma),
924            new_dma!(rx_dma),
925            config,
926        )
927    }
928
929    /// Half-duplex
930    ///
931    /// Note: Half duplex requires TX pin to have a pull-up resistor
932    pub fn new_half_duplex<#[cfg(not(afio_h4))] const REMAP: u8>(
933        _peri: Peri<'d, T>,
934        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
935        tx_dma: Peri<'d, impl TxDma<T>>,
936        rx_dma: Peri<'d, impl RxDma<T>>,
937        mut config: Config,
938    ) -> Result<Self, ConfigError> {
939        apply_remap!();
940        // gpio_x0 doesn't expose an open-drain AF variant; fall back to push-pull
941        // and rely on the user to provide an external pull-up.
942        #[cfg(not(gpio_x0))]
943        let tx_af = AfType::output(OutputType::OpenDrain, Speed::High);
944        #[cfg(gpio_x0)]
945        let tx_af = AfType::output(OutputType::PushPull, Speed::High);
946        config.half_duplex = true;
947
948        Self::new_inner(
949            _peri,
950            None,
951            new_pin!(tx, tx_af),
952            None,
953            None,
954            new_dma!(tx_dma),
955            new_dma!(rx_dma),
956            config
957        )
958    }
959}
960
961impl<'d, T: Instance> Uart<'d, T, Blocking> {
962    /// Create a new blocking bidirectional UART.
963    pub fn new_blocking<#[cfg(not(afio_h4))] const REMAP: u8>(
964        peri: Peri<'d, T>,
965        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
966        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
967        config: Config,
968    ) -> Result<Self, ConfigError> {
969        apply_remap!();
970        Self::new_inner(
971            peri,
972            new_pin!(rx, AfType::input(Pull::None)),
973            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)),
974            None,
975            None,
976            None,
977            None,
978            config,
979        )
980    }
981
982    /// Create a new bidirectional UART with request-to-send and clear-to-send pins
983    pub fn new_blocking_with_rtscts<#[cfg(not(afio_h4))] const REMAP: u8>(
984        peri: Peri<'d, T>,
985        rx: Peri<'d, if_remap!(impl RxPin<T, REMAP>)>,
986        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
987        rts: Peri<'d, if_remap!(impl RtsPin<T, REMAP>)>,
988        cts: Peri<'d, if_remap!(impl CtsPin<T, REMAP>)>,
989        config: Config,
990    ) -> Result<Self, ConfigError> {
991        apply_remap!();
992        Self::new_inner(
993            peri,
994            new_pin!(rx, AfType::input(Pull::None)),
995            new_pin!(tx, AfType::output(OutputType::PushPull, Speed::High)),
996            new_pin!(rts, AfType::output(OutputType::PushPull, Speed::High)),
997            new_pin!(cts, AfType::input(Pull::None)),
998            None,
999            None,
1000            config,
1001        )
1002    }
1003
1004    pub fn new_blocking_half_duplex<#[cfg(not(afio_h4))] const REMAP: u8>(
1005        peri: Peri<'d, T>,
1006        tx: Peri<'d, if_remap!(impl TxPin<T, REMAP>)>,
1007        mut config: Config,
1008    ) -> Result<Self, ConfigError> {
1009        apply_remap!();
1010        #[cfg(not(gpio_x0))]
1011        let tx_af = AfType::output(OutputType::OpenDrain, Speed::High);
1012        #[cfg(gpio_x0)]
1013        let tx_af = AfType::output(OutputType::PushPull, Speed::High);
1014        config.half_duplex = true;
1015
1016        Self::new_inner(peri, None, new_pin!(tx, tx_af), None, None, None, None, config)
1017    }
1018}
1019
1020fn reconfigure<T: Instance>(config: &Config) -> Result<(), ConfigError> {
1021    baudrate_divisor(T::frequency().0, config.baudrate)?;
1022    let enabled = T::Interrupt::is_enabled();
1023    T::Interrupt::disable();
1024    let r = T::regs();
1025
1026    let cr = r.ctlr1().read();
1027    configure(&r, config, T::frequency(), cr.te(), cr.re())?;
1028
1029    T::Interrupt::unpend();
1030    if enabled {
1031        unsafe { T::Interrupt::enable() };
1032    }
1033
1034    Ok(())
1035}
1036
1037fn configure(
1038    rb: &pac::usart::Usart,
1039    config: &Config,
1040    pclk_freq: Hertz,
1041    enable_tx: bool,
1042    enable_rx: bool,
1043) -> Result<(), ConfigError> {
1044    let divisor = baudrate_divisor(pclk_freq.0, config.baudrate)?;
1045    if !enable_rx && !enable_tx {
1046        panic!("USART: At least one of RX or TX should be enabled");
1047    }
1048
1049    rb.ctlr1().modify(|register| register.set_ue(false));
1050    rb.ctlr2().modify(|w| w.set_stop(config.stop_bits as u8));
1051
1052    rb.ctlr1().modify(|w| {
1053        w.set_m(config.data_bits as u8 != 0);
1054        w.set_pce(config.parity != Parity::ParityNone);
1055        w.set_ps(config.parity == Parity::ParityOdd); // 1 for odd parity, 0 for even parity
1056        w.set_te(enable_tx);
1057        w.set_re(enable_rx);
1058    });
1059
1060    rb.ctlr3().modify(|w| w.set_hdsel(config.half_duplex));
1061
1062    rb.brr().write(|w| w.0 = divisor);
1063
1064    // enable uart
1065    rb.ctlr1().modify(|w| w.set_ue(true));
1066
1067    Ok(())
1068}
1069
1070fn baudrate_divisor(clock_hz: u32, baudrate: u32) -> Result<u32, ConfigError> {
1071    if baudrate == 0 {
1072        return Err(ConfigError::BaudrateTooLow);
1073    }
1074    // BRR holds USARTDIV in 4.16 fixed point, and the hardware requires
1075    // USARTDIV >= 1 (BRR >= 0x10), which the documented maximum baud rate
1076    // equals: 3 Mbps at 48 MHz, 4.5 at 72, 9 at 144 and 12.5 at 200.
1077    let divisor = (u64::from(clock_hz) + u64::from(baudrate) / 2) / u64::from(baudrate);
1078    if divisor < 0x10 {
1079        return Err(ConfigError::BaudrateTooHigh);
1080    }
1081    if divisor > 0xffff {
1082        return Err(ConfigError::BaudrateTooLow);
1083    }
1084    Ok(divisor as u32)
1085}
1086
1087fn receive_error(status: pac::usart::regs::Statr) -> Option<Error> {
1088    if status.pe() {
1089        Some(Error::Parity)
1090    } else if status.fe() {
1091        Some(Error::Framing)
1092    } else if status.ne() {
1093        Some(Error::Noise)
1094    } else if status.ore() {
1095        Some(Error::Overrun)
1096    } else {
1097        None
1098    }
1099}
1100
1101fn enable_peripheral<T: Instance>() {
1102    #[cfg(usart_v4x7)]
1103    critical_section::with(|cs| {
1104        let count = T::state().users.load(Ordering::Relaxed);
1105        if count == 0 {
1106            T::enable_and_reset_with_cs(cs);
1107        }
1108        T::state().users.store(count + 1, Ordering::Relaxed);
1109    });
1110    #[cfg(not(usart_v4x7))]
1111    T::enable_and_reset();
1112}
1113
1114fn disable_peripheral<T: Instance>() {
1115    #[cfg(usart_v4x7)]
1116    critical_section::with(|cs| {
1117        let count = T::state().users.load(Ordering::Relaxed);
1118        assert!(count != 0);
1119        T::state().users.store(count - 1, Ordering::Relaxed);
1120        if count == 1 {
1121            T::regs().ctlr1().write(|register| register.set_ue(false));
1122            T::regs().ctlr3().write(|register| register.set_dmar(false));
1123            T::Interrupt::disable();
1124            T::Interrupt::unpend();
1125            T::disable_with_cs(cs);
1126        }
1127    });
1128    #[cfg(not(usart_v4x7))]
1129    T::disable();
1130}
1131
1132impl<'d, T: Instance> core::fmt::Write for UartTx<'d, T, Blocking> {
1133    fn write_str(&mut self, s: &str) -> core::fmt::Result {
1134        self.blocking_write(s.as_bytes()).map_err(|_| core::fmt::Error)?;
1135        Ok(())
1136    }
1137}
1138impl<'d, T: Instance> core::fmt::Write for Uart<'d, T, Blocking> {
1139    fn write_str(&mut self, s: &str) -> core::fmt::Result {
1140        self.blocking_write(s.as_bytes()).map_err(|_| core::fmt::Error)?;
1141        Ok(())
1142    }
1143}
1144
1145// Peripheral traits
1146struct State {
1147    #[cfg(usart_v4x7)]
1148    users: AtomicUsize,
1149    #[allow(unused)]
1150    rx_waker: AtomicWaker,
1151    tx_waker: AtomicWaker,
1152    /// PE/FE/NE/ORE bits the interrupt handler observed, latched for the
1153    /// reader because clearing them from the register races with the DMA.
1154    rx_errors: AtomicU32,
1155}
1156
1157impl State {
1158    const fn new() -> Self {
1159        Self {
1160            #[cfg(usart_v4x7)]
1161            users: AtomicUsize::new(0),
1162            rx_waker: AtomicWaker::new(),
1163            tx_waker: AtomicWaker::new(),
1164            rx_errors: AtomicU32::new(0),
1165        }
1166    }
1167}
1168
1169trait SealedInstance: crate::peripheral::RccPeripheral {
1170    fn regs() -> crate::pac::usart::Usart;
1171    fn state() -> &'static State;
1172
1173    // fn buffered_state() -> &'static buffered::State;
1174}
1175
1176#[allow(private_bounds)]
1177pub trait Instance: embassy_hal_internal::PeripheralType + SealedInstance + crate::peripheral::RemapBound + 'static + Send {
1178    /// Interrupt for this instance.
1179    type Interrupt: interrupt::typelevel::Interrupt;
1180}
1181
1182foreach_peripheral!(
1183    (usart, $inst:ident) => {
1184        impl SealedInstance for peripherals::$inst {
1185            fn regs() -> crate::pac::usart::Usart {
1186                crate::pac::$inst
1187            }
1188
1189            fn state() -> &'static State {
1190                static STATE: State = State::new();
1191                &STATE
1192            }
1193        }
1194
1195        impl Instance for peripherals::$inst {
1196            type Interrupt = crate::_generated::peripheral_interrupts::$inst::GLOBAL;
1197        }
1198    };
1199);
1200
1201pin_trait!(RxPin, Instance);
1202pin_trait!(TxPin, Instance);
1203pin_trait!(CtsPin, Instance);
1204pin_trait!(RtsPin, Instance);
1205pin_trait!(CkPin, Instance);
1206
1207dma_trait!(TxDma, Instance);
1208dma_trait!(RxDma, Instance);
1209