embassy_stm32/usart/
mod.rs

1//! Universal Synchronous/Asynchronous Receiver Transmitter (USART, UART, LPUART)
2#![macro_use]
3#![warn(missing_docs)]
4
5use core::future::poll_fn;
6use core::marker::PhantomData;
7use core::sync::atomic::{compiler_fence, AtomicU8, Ordering};
8use core::task::Poll;
9
10use embassy_embedded_hal::SetConfig;
11use embassy_hal_internal::drop::OnDrop;
12use embassy_hal_internal::PeripheralType;
13use embassy_sync::waitqueue::AtomicWaker;
14use futures_util::future::{select, Either};
15
16use crate::dma::ChannelAndRequest;
17use crate::gpio::{AfType, AnyPin, OutputType, Pull, SealedPin as _, Speed};
18use crate::interrupt::typelevel::Interrupt as _;
19use crate::interrupt::{self, Interrupt, InterruptExt};
20use crate::mode::{Async, Blocking, Mode};
21#[cfg(not(any(usart_v1, usart_v2)))]
22use crate::pac::usart::Lpuart as Regs;
23#[cfg(any(usart_v1, usart_v2))]
24use crate::pac::usart::Usart as Regs;
25use crate::pac::usart::{regs, vals};
26use crate::rcc::{RccInfo, SealedRccPeripheral};
27use crate::time::Hertz;
28use crate::Peri;
29
30/// Interrupt handler.
31pub struct InterruptHandler<T: Instance> {
32    _phantom: PhantomData<T>,
33}
34
35impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
36    unsafe fn on_interrupt() {
37        on_interrupt(T::info().regs, T::state())
38    }
39}
40
41unsafe fn on_interrupt(r: Regs, s: &'static State) {
42    let (sr, cr1, cr3) = (sr(r).read(), r.cr1().read(), r.cr3().read());
43
44    let has_errors = (sr.pe() && cr1.peie()) || ((sr.fe() || sr.ne() || sr.ore()) && cr3.eie());
45    if has_errors {
46        // clear all interrupts and DMA Rx Request
47        r.cr1().modify(|w| {
48            // disable RXNE interrupt
49            w.set_rxneie(false);
50            // disable parity interrupt
51            w.set_peie(false);
52            // disable idle line interrupt
53            w.set_idleie(false);
54        });
55        r.cr3().modify(|w| {
56            // disable Error Interrupt: (Frame error, Noise error, Overrun error)
57            w.set_eie(false);
58            // disable DMA Rx Request
59            w.set_dmar(false);
60        });
61    } else if cr1.idleie() && sr.idle() {
62        // IDLE detected: no more data will come
63        r.cr1().modify(|w| {
64            // disable idle line detection
65            w.set_idleie(false);
66        });
67    } else if cr1.tcie() && sr.tc() {
68        // Transmission complete detected
69        r.cr1().modify(|w| {
70            // disable Transmission complete interrupt
71            w.set_tcie(false);
72        });
73    } else if cr1.rxneie() {
74        // We cannot check the RXNE flag as it is auto-cleared by the DMA controller
75
76        // It is up to the listener to determine if this in fact was a RX event and disable the RXNE detection
77    } else {
78        return;
79    }
80
81    compiler_fence(Ordering::SeqCst);
82    s.rx_waker.wake();
83    s.tx_waker.wake();
84}
85
86#[derive(Clone, Copy, PartialEq, Eq, Debug)]
87#[cfg_attr(feature = "defmt", derive(defmt::Format))]
88/// Number of data bits
89pub enum DataBits {
90    /// 7 Data Bits
91    DataBits7,
92    /// 8 Data Bits
93    DataBits8,
94    /// 9 Data Bits
95    DataBits9,
96}
97
98#[derive(Clone, Copy, PartialEq, Eq, Debug)]
99#[cfg_attr(feature = "defmt", derive(defmt::Format))]
100/// Parity
101pub enum Parity {
102    /// No parity
103    ParityNone,
104    /// Even Parity
105    ParityEven,
106    /// Odd Parity
107    ParityOdd,
108}
109
110#[derive(Clone, Copy, PartialEq, Eq, Debug)]
111#[cfg_attr(feature = "defmt", derive(defmt::Format))]
112/// Number of stop bits
113pub enum StopBits {
114    #[doc = "1 stop bit"]
115    STOP1,
116    #[doc = "0.5 stop bits"]
117    STOP0P5,
118    #[doc = "2 stop bits"]
119    STOP2,
120    #[doc = "1.5 stop bits"]
121    STOP1P5,
122}
123
124#[derive(Clone, Copy, PartialEq, Eq, Debug)]
125#[cfg_attr(feature = "defmt", derive(defmt::Format))]
126/// Enables or disables receiver so written data are read back in half-duplex mode
127pub enum HalfDuplexReadback {
128    /// Disables receiver so written data are not read back
129    NoReadback,
130    /// Enables receiver so written data are read back
131    Readback,
132}
133
134#[derive(Clone, Copy, PartialEq, Eq, Debug)]
135#[cfg_attr(feature = "defmt", derive(defmt::Format))]
136/// Half duplex IO mode
137pub enum OutputConfig {
138    /// Push pull allows for faster baudrates, no internal pullup
139    PushPull,
140    /// Open drain output (external pull up needed)
141    OpenDrain,
142    #[cfg(not(gpio_v1))]
143    /// Open drain output with internal pull up resistor
144    OpenDrainPullUp,
145}
146
147impl OutputConfig {
148    const fn af_type(self) -> AfType {
149        match self {
150            OutputConfig::PushPull => AfType::output(OutputType::PushPull, Speed::Medium),
151            OutputConfig::OpenDrain => AfType::output(OutputType::OpenDrain, Speed::Medium),
152            #[cfg(not(gpio_v1))]
153            OutputConfig::OpenDrainPullUp => AfType::output_pull(OutputType::OpenDrain, Speed::Medium, Pull::Up),
154        }
155    }
156}
157
158#[derive(Clone, Copy, PartialEq, Eq, Debug)]
159#[cfg_attr(feature = "defmt", derive(defmt::Format))]
160/// Duplex mode
161pub enum Duplex {
162    /// Full duplex
163    Full,
164    /// Half duplex with possibility to read back written data
165    Half(HalfDuplexReadback),
166}
167
168impl Duplex {
169    /// Returns true if half-duplex
170    fn is_half(&self) -> bool {
171        matches!(self, Duplex::Half(_))
172    }
173}
174
175#[non_exhaustive]
176#[derive(Clone, Copy, PartialEq, Eq, Debug)]
177#[cfg_attr(feature = "defmt", derive(defmt::Format))]
178/// Config Error
179pub enum ConfigError {
180    /// Baudrate too low
181    BaudrateTooLow,
182    /// Baudrate too high
183    BaudrateTooHigh,
184    /// Rx or Tx not enabled
185    RxOrTxNotEnabled,
186    /// Data bits and parity combination not supported
187    DataParityNotSupported,
188}
189
190#[non_exhaustive]
191#[derive(Clone, Copy, PartialEq, Eq, Debug)]
192/// Config
193pub struct Config {
194    /// Baud rate
195    pub baudrate: u32,
196    /// Number of data bits
197    pub data_bits: DataBits,
198    /// Number of stop bits
199    pub stop_bits: StopBits,
200    /// Parity type
201    pub parity: Parity,
202
203    /// If true: on a read-like method, if there is a latent error pending,
204    /// the read will abort and the error will be reported and cleared
205    ///
206    /// If false: the error is ignored and cleared
207    pub detect_previous_overrun: bool,
208
209    /// Set this to true if the line is considered noise free.
210    /// This will increase the receiver’s tolerance to clock deviations,
211    /// but will effectively disable noise detection.
212    #[cfg(not(usart_v1))]
213    pub assume_noise_free: bool,
214
215    /// Set this to true to swap the RX and TX pins.
216    #[cfg(any(usart_v3, usart_v4))]
217    pub swap_rx_tx: bool,
218
219    /// Set this to true to invert TX pin signal values (V<sub>DD</sub> = 0/mark, Gnd = 1/idle).
220    #[cfg(any(usart_v3, usart_v4))]
221    pub invert_tx: bool,
222
223    /// Set this to true to invert RX pin signal values (V<sub>DD</sub> = 0/mark, Gnd = 1/idle).
224    #[cfg(any(usart_v3, usart_v4))]
225    pub invert_rx: bool,
226
227    /// Set the pull configuration for the RX pin.
228    pub rx_pull: Pull,
229
230    /// Set the pull configuration for the CTS pin.
231    pub cts_pull: Pull,
232
233    /// Set the pin configuration for the TX pin.
234    pub tx_config: OutputConfig,
235
236    /// Set the pin configuration for the RTS pin.
237    pub rts_config: OutputConfig,
238
239    /// Set the pin configuration for the DE pin.
240    pub de_config: OutputConfig,
241
242    // private: set by new_half_duplex, not by the user.
243    duplex: Duplex,
244}
245
246impl Config {
247    fn tx_af(&self) -> AfType {
248        #[cfg(any(usart_v3, usart_v4))]
249        if self.swap_rx_tx {
250            return AfType::input(self.rx_pull);
251        };
252        self.tx_config.af_type()
253    }
254
255    fn rx_af(&self) -> AfType {
256        #[cfg(any(usart_v3, usart_v4))]
257        if self.swap_rx_tx {
258            return self.tx_config.af_type();
259        };
260        AfType::input(self.rx_pull)
261    }
262}
263
264impl Default for Config {
265    fn default() -> Self {
266        Self {
267            baudrate: 115200,
268            data_bits: DataBits::DataBits8,
269            stop_bits: StopBits::STOP1,
270            parity: Parity::ParityNone,
271            // historical behavior
272            detect_previous_overrun: false,
273            #[cfg(not(usart_v1))]
274            assume_noise_free: false,
275            #[cfg(any(usart_v3, usart_v4))]
276            swap_rx_tx: false,
277            #[cfg(any(usart_v3, usart_v4))]
278            invert_tx: false,
279            #[cfg(any(usart_v3, usart_v4))]
280            invert_rx: false,
281            rx_pull: Pull::None,
282            cts_pull: Pull::None,
283            tx_config: OutputConfig::PushPull,
284            rts_config: OutputConfig::PushPull,
285            de_config: OutputConfig::PushPull,
286            duplex: Duplex::Full,
287        }
288    }
289}
290
291/// Serial error
292#[derive(Debug, Eq, PartialEq, Copy, Clone)]
293#[cfg_attr(feature = "defmt", derive(defmt::Format))]
294#[non_exhaustive]
295pub enum Error {
296    /// Framing error
297    Framing,
298    /// Noise error
299    Noise,
300    /// RX buffer overrun
301    Overrun,
302    /// Parity check error
303    Parity,
304    /// Buffer too large for DMA
305    BufferTooLong,
306}
307
308impl core::fmt::Display for Error {
309    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
310        let message = match self {
311            Self::Framing => "Framing Error",
312            Self::Noise => "Noise Error",
313            Self::Overrun => "RX Buffer Overrun",
314            Self::Parity => "Parity Check Error",
315            Self::BufferTooLong => "Buffer too large for DMA",
316        };
317
318        write!(f, "{}", message)
319    }
320}
321
322impl core::error::Error for Error {}
323
324enum ReadCompletionEvent {
325    // DMA Read transfer completed first
326    DmaCompleted,
327    // Idle line detected first
328    Idle(usize),
329}
330
331/// Bidirectional UART Driver, which acts as a combination of [`UartTx`] and [`UartRx`].
332///
333/// ### Notes on [`embedded_io::Read`]
334///
335/// `embedded_io::Read` requires guarantees that the base [`UartRx`] cannot provide.
336///
337/// See [`UartRx`] for more details, and see [`BufferedUart`] and [`RingBufferedUartRx`]
338/// as alternatives that do provide the necessary guarantees for `embedded_io::Read`.
339pub struct Uart<'d, M: Mode> {
340    tx: UartTx<'d, M>,
341    rx: UartRx<'d, M>,
342}
343
344impl<'d, M: Mode> SetConfig for Uart<'d, M> {
345    type Config = Config;
346    type ConfigError = ConfigError;
347
348    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
349        self.tx.set_config(config)?;
350        self.rx.set_config(config)
351    }
352}
353
354/// Tx-only UART Driver.
355///
356/// Can be obtained from [`Uart::split`], or can be constructed independently,
357/// if you do not need the receiving half of the driver.
358pub struct UartTx<'d, M: Mode> {
359    info: &'static Info,
360    state: &'static State,
361    kernel_clock: Hertz,
362    tx: Option<Peri<'d, AnyPin>>,
363    cts: Option<Peri<'d, AnyPin>>,
364    de: Option<Peri<'d, AnyPin>>,
365    tx_dma: Option<ChannelAndRequest<'d>>,
366    duplex: Duplex,
367    _phantom: PhantomData<M>,
368}
369
370impl<'d, M: Mode> SetConfig for UartTx<'d, M> {
371    type Config = Config;
372    type ConfigError = ConfigError;
373
374    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
375        self.set_config(config)
376    }
377}
378
379/// Rx-only UART Driver.
380///
381/// Can be obtained from [`Uart::split`], or can be constructed independently,
382/// if you do not need the transmitting half of the driver.
383///
384/// ### Notes on [`embedded_io::Read`]
385///
386/// `embedded_io::Read` requires guarantees that this struct cannot provide:
387///
388/// - Any data received between calls to [`UartRx::read`] or [`UartRx::blocking_read`]
389/// will be thrown away, as `UartRx` is unbuffered.
390/// Users of `embedded_io::Read` are likely to not expect this behavior
391/// (for instance if they read multiple small chunks in a row).
392/// - [`UartRx::read`] and [`UartRx::blocking_read`] only return once the entire buffer has been
393/// filled, whereas `embedded_io::Read` requires us to fill the buffer with what we already
394/// received, and only block/wait until the first byte arrived.
395/// <br />
396/// While [`UartRx::read_until_idle`] does return early, it will still eagerly wait for data until
397/// the buffer is full or no data has been transmitted in a while,
398/// which may not be what users of `embedded_io::Read` expect.
399///
400/// [`UartRx::into_ring_buffered`] can be called to equip `UartRx` with a buffer,
401/// that it can then use to store data received between calls to `read`,
402/// provided you are using DMA already.
403///
404/// Alternatively, you can use [`BufferedUartRx`], which is interrupt-based and which can also
405/// store data received between calls.
406///
407/// Also see [this github comment](https://github.com/embassy-rs/embassy/pull/2185#issuecomment-1810047043).
408pub struct UartRx<'d, M: Mode> {
409    info: &'static Info,
410    state: &'static State,
411    kernel_clock: Hertz,
412    rx: Option<Peri<'d, AnyPin>>,
413    rts: Option<Peri<'d, AnyPin>>,
414    rx_dma: Option<ChannelAndRequest<'d>>,
415    detect_previous_overrun: bool,
416    #[cfg(any(usart_v1, usart_v2))]
417    buffered_sr: regs::Sr,
418    _phantom: PhantomData<M>,
419}
420
421impl<'d, M: Mode> SetConfig for UartRx<'d, M> {
422    type Config = Config;
423    type ConfigError = ConfigError;
424
425    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
426        self.set_config(config)
427    }
428}
429
430impl<'d> UartTx<'d, Async> {
431    /// Useful if you only want Uart Tx. It saves 1 pin and consumes a little less power.
432    pub fn new<T: Instance>(
433        peri: Peri<'d, T>,
434        tx: Peri<'d, impl TxPin<T>>,
435        tx_dma: Peri<'d, impl TxDma<T>>,
436        config: Config,
437    ) -> Result<Self, ConfigError> {
438        Self::new_inner(peri, new_pin!(tx, config.tx_af()), None, new_dma!(tx_dma), config)
439    }
440
441    /// Create a new tx-only UART with a clear-to-send pin
442    pub fn new_with_cts<T: Instance>(
443        peri: Peri<'d, T>,
444        tx: Peri<'d, impl TxPin<T>>,
445        cts: Peri<'d, impl CtsPin<T>>,
446        tx_dma: Peri<'d, impl TxDma<T>>,
447        config: Config,
448    ) -> Result<Self, ConfigError> {
449        Self::new_inner(
450            peri,
451            new_pin!(tx, config.tx_af()),
452            new_pin!(cts, AfType::input(config.cts_pull)),
453            new_dma!(tx_dma),
454            config,
455        )
456    }
457
458    /// Initiate an asynchronous UART write
459    pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
460        let r = self.info.regs;
461
462        half_duplex_set_rx_tx_before_write(&r, self.duplex == Duplex::Half(HalfDuplexReadback::Readback));
463
464        let ch = self.tx_dma.as_mut().unwrap();
465        r.cr3().modify(|reg| {
466            reg.set_dmat(true);
467        });
468        // If we don't assign future to a variable, the data register pointer
469        // is held across an await and makes the future non-Send.
470        let transfer = unsafe { ch.write(buffer, tdr(r), Default::default()) };
471        transfer.await;
472        Ok(())
473    }
474
475    /// Wait until transmission complete
476    pub async fn flush(&mut self) -> Result<(), Error> {
477        flush(&self.info, &self.state).await
478    }
479}
480
481impl<'d> UartTx<'d, Blocking> {
482    /// Create a new blocking tx-only UART with no hardware flow control.
483    ///
484    /// Useful if you only want Uart Tx. It saves 1 pin and consumes a little less power.
485    pub fn new_blocking<T: Instance>(
486        peri: Peri<'d, T>,
487        tx: Peri<'d, impl TxPin<T>>,
488        config: Config,
489    ) -> Result<Self, ConfigError> {
490        Self::new_inner(peri, new_pin!(tx, config.tx_af()), None, None, config)
491    }
492
493    /// Create a new blocking tx-only UART with a clear-to-send pin
494    pub fn new_blocking_with_cts<T: Instance>(
495        peri: Peri<'d, T>,
496        tx: Peri<'d, impl TxPin<T>>,
497        cts: Peri<'d, impl CtsPin<T>>,
498        config: Config,
499    ) -> Result<Self, ConfigError> {
500        Self::new_inner(
501            peri,
502            new_pin!(tx, config.tx_af()),
503            new_pin!(cts, AfType::input(config.cts_pull)),
504            None,
505            config,
506        )
507    }
508}
509
510impl<'d, M: Mode> UartTx<'d, M> {
511    fn new_inner<T: Instance>(
512        _peri: Peri<'d, T>,
513        tx: Option<Peri<'d, AnyPin>>,
514        cts: Option<Peri<'d, AnyPin>>,
515        tx_dma: Option<ChannelAndRequest<'d>>,
516        config: Config,
517    ) -> Result<Self, ConfigError> {
518        let mut this = Self {
519            info: T::info(),
520            state: T::state(),
521            kernel_clock: T::frequency(),
522            tx,
523            cts,
524            de: None,
525            tx_dma,
526            duplex: config.duplex,
527            _phantom: PhantomData,
528        };
529        this.enable_and_configure(&config)?;
530        Ok(this)
531    }
532
533    fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> {
534        let info = self.info;
535        let state = self.state;
536        state.tx_rx_refcount.store(1, Ordering::Relaxed);
537
538        info.rcc.enable_and_reset();
539
540        info.regs.cr3().modify(|w| {
541            w.set_ctse(self.cts.is_some());
542        });
543        configure(info, self.kernel_clock, config, false, true)?;
544
545        Ok(())
546    }
547
548    /// Reconfigure the driver
549    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
550        reconfigure(self.info, self.kernel_clock, config)
551    }
552
553    /// Write a single u8 if there is tx empty, otherwise return WouldBlock
554    pub(crate) fn nb_write(&mut self, byte: u8) -> Result<(), nb::Error<Error>> {
555        let r = self.info.regs;
556        let sr = sr(r).read();
557        if sr.txe() {
558            unsafe {
559                tdr(r).write_volatile(byte);
560            }
561            Ok(())
562        } else {
563            Err(nb::Error::WouldBlock)
564        }
565    }
566
567    /// Perform a blocking UART write
568    pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
569        let r = self.info.regs;
570
571        half_duplex_set_rx_tx_before_write(&r, self.duplex == Duplex::Half(HalfDuplexReadback::Readback));
572
573        for &b in buffer {
574            while !sr(r).read().txe() {}
575            unsafe { tdr(r).write_volatile(b) };
576        }
577        Ok(())
578    }
579
580    /// Block until transmission complete
581    pub fn blocking_flush(&mut self) -> Result<(), Error> {
582        blocking_flush(self.info)
583    }
584
585    /// Send break character
586    pub fn send_break(&self) {
587        send_break(&self.info.regs);
588    }
589
590    /// Set baudrate
591    pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
592        set_baudrate(self.info, self.kernel_clock, baudrate)
593    }
594}
595
596/// Wait until transmission complete
597async fn flush(info: &Info, state: &State) -> Result<(), Error> {
598    let r = info.regs;
599    if r.cr1().read().te() && !sr(r).read().tc() {
600        r.cr1().modify(|w| {
601            // enable Transmission Complete interrupt
602            w.set_tcie(true);
603        });
604
605        compiler_fence(Ordering::SeqCst);
606
607        // future which completes when Transmission complete is detected
608        let abort = poll_fn(move |cx| {
609            state.tx_waker.register(cx.waker());
610
611            let sr = sr(r).read();
612            if sr.tc() {
613                // Transmission complete detected
614                return Poll::Ready(());
615            }
616
617            Poll::Pending
618        });
619
620        abort.await;
621    }
622
623    Ok(())
624}
625
626fn blocking_flush(info: &Info) -> Result<(), Error> {
627    let r = info.regs;
628    if r.cr1().read().te() {
629        while !sr(r).read().tc() {}
630    }
631
632    Ok(())
633}
634
635/// Send break character
636pub fn send_break(regs: &Regs) {
637    // Busy wait until previous break has been sent
638    #[cfg(any(usart_v1, usart_v2))]
639    while regs.cr1().read().sbk() {}
640    #[cfg(any(usart_v3, usart_v4))]
641    while regs.isr().read().sbkf() {}
642
643    // Send break right after completing the current character transmission
644    #[cfg(any(usart_v1, usart_v2))]
645    regs.cr1().modify(|w| w.set_sbk(true));
646    #[cfg(any(usart_v3, usart_v4))]
647    regs.rqr().write(|w| w.set_sbkrq(true));
648}
649
650/// Enable Transmitter and disable Receiver for Half-Duplex mode
651/// In case of readback, keep Receiver enabled
652fn half_duplex_set_rx_tx_before_write(r: &Regs, enable_readback: bool) {
653    let mut cr1 = r.cr1().read();
654    if r.cr3().read().hdsel() {
655        cr1.set_te(true);
656        cr1.set_re(enable_readback);
657        r.cr1().write_value(cr1);
658    }
659}
660
661impl<'d> UartRx<'d, Async> {
662    /// Create a new rx-only UART with no hardware flow control.
663    ///
664    /// Useful if you only want Uart Rx. It saves 1 pin and consumes a little less power.
665    pub fn new<T: Instance>(
666        peri: Peri<'d, T>,
667        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
668        rx: Peri<'d, impl RxPin<T>>,
669        rx_dma: Peri<'d, impl RxDma<T>>,
670        config: Config,
671    ) -> Result<Self, ConfigError> {
672        Self::new_inner(peri, new_pin!(rx, config.rx_af()), None, new_dma!(rx_dma), config)
673    }
674
675    /// Create a new rx-only UART with a request-to-send pin
676    pub fn new_with_rts<T: Instance>(
677        peri: Peri<'d, T>,
678        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
679        rx: Peri<'d, impl RxPin<T>>,
680        rts: Peri<'d, impl RtsPin<T>>,
681        rx_dma: Peri<'d, impl RxDma<T>>,
682        config: Config,
683    ) -> Result<Self, ConfigError> {
684        Self::new_inner(
685            peri,
686            new_pin!(rx, config.rx_af()),
687            new_pin!(rts, config.rts_config.af_type()),
688            new_dma!(rx_dma),
689            config,
690        )
691    }
692
693    /// Initiate an asynchronous UART read
694    pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
695        self.inner_read(buffer, false).await?;
696
697        Ok(())
698    }
699
700    /// Initiate an asynchronous read with idle line detection enabled
701    pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
702        self.inner_read(buffer, true).await
703    }
704
705    async fn inner_read_run(
706        &mut self,
707        buffer: &mut [u8],
708        enable_idle_line_detection: bool,
709    ) -> Result<ReadCompletionEvent, Error> {
710        let r = self.info.regs;
711
712        // Call flush for Half-Duplex mode if some bytes were written and flush was not called.
713        // It prevents reading of bytes which have just been written.
714        if r.cr3().read().hdsel() && r.cr1().read().te() {
715            flush(&self.info, &self.state).await?;
716
717            // Disable Transmitter and enable Receiver after flush
718            r.cr1().modify(|reg| {
719                reg.set_re(true);
720                reg.set_te(false);
721            });
722        }
723
724        // make sure USART state is restored to neutral state when this future is dropped
725        let on_drop = OnDrop::new(move || {
726            // clear all interrupts and DMA Rx Request
727            r.cr1().modify(|w| {
728                // disable RXNE interrupt
729                w.set_rxneie(false);
730                // disable parity interrupt
731                w.set_peie(false);
732                // disable idle line interrupt
733                w.set_idleie(false);
734            });
735            r.cr3().modify(|w| {
736                // disable Error Interrupt: (Frame error, Noise error, Overrun error)
737                w.set_eie(false);
738                // disable DMA Rx Request
739                w.set_dmar(false);
740            });
741        });
742
743        let ch = self.rx_dma.as_mut().unwrap();
744
745        let buffer_len = buffer.len();
746
747        // Start USART DMA
748        // will not do anything yet because DMAR is not yet set
749        // future which will complete when DMA Read request completes
750        let transfer = unsafe { ch.read(rdr(r), buffer, Default::default()) };
751
752        // clear ORE flag just before enabling DMA Rx Request: can be mandatory for the second transfer
753        if !self.detect_previous_overrun {
754            let sr = sr(r).read();
755            // This read also clears the error and idle interrupt flags on v1.
756            unsafe { rdr(r).read_volatile() };
757            clear_interrupt_flags(r, sr);
758        }
759
760        r.cr1().modify(|w| {
761            // disable RXNE interrupt
762            w.set_rxneie(false);
763            // enable parity interrupt if not ParityNone
764            w.set_peie(w.pce());
765        });
766
767        r.cr3().modify(|w| {
768            // enable Error Interrupt: (Frame error, Noise error, Overrun error)
769            w.set_eie(true);
770            // enable DMA Rx Request
771            w.set_dmar(true);
772        });
773
774        compiler_fence(Ordering::SeqCst);
775
776        // In case of errors already pending when reception started, interrupts may have already been raised
777        // and lead to reception abortion (Overrun error for instance). In such a case, all interrupts
778        // have been disabled in interrupt handler and DMA Rx Request has been disabled.
779
780        let cr3 = r.cr3().read();
781
782        if !cr3.dmar() {
783            // something went wrong
784            // because the only way to get this flag cleared is to have an interrupt
785
786            // DMA will be stopped when transfer is dropped
787
788            let sr = sr(r).read();
789            // This read also clears the error and idle interrupt flags on v1.
790            unsafe { rdr(r).read_volatile() };
791            clear_interrupt_flags(r, sr);
792
793            if sr.pe() {
794                return Err(Error::Parity);
795            }
796            if sr.fe() {
797                return Err(Error::Framing);
798            }
799            if sr.ne() {
800                return Err(Error::Noise);
801            }
802            if sr.ore() {
803                return Err(Error::Overrun);
804            }
805
806            unreachable!();
807        }
808
809        if enable_idle_line_detection {
810            // clear idle flag
811            let sr = sr(r).read();
812            // This read also clears the error and idle interrupt flags on v1.
813            unsafe { rdr(r).read_volatile() };
814            clear_interrupt_flags(r, sr);
815
816            // enable idle interrupt
817            r.cr1().modify(|w| {
818                w.set_idleie(true);
819            });
820        }
821
822        compiler_fence(Ordering::SeqCst);
823
824        // future which completes when idle line or error is detected
825        let s = self.state;
826        let abort = poll_fn(move |cx| {
827            s.rx_waker.register(cx.waker());
828
829            let sr = sr(r).read();
830
831            // This read also clears the error and idle interrupt flags on v1.
832            unsafe { rdr(r).read_volatile() };
833            clear_interrupt_flags(r, sr);
834
835            if enable_idle_line_detection {
836                // enable idle interrupt
837                r.cr1().modify(|w| {
838                    w.set_idleie(true);
839                });
840            }
841
842            compiler_fence(Ordering::SeqCst);
843
844            let has_errors = sr.pe() || sr.fe() || sr.ne() || sr.ore();
845
846            if has_errors {
847                // all Rx interrupts and Rx DMA Request have already been cleared in interrupt handler
848
849                if sr.pe() {
850                    return Poll::Ready(Err(Error::Parity));
851                }
852                if sr.fe() {
853                    return Poll::Ready(Err(Error::Framing));
854                }
855                if sr.ne() {
856                    return Poll::Ready(Err(Error::Noise));
857                }
858                if sr.ore() {
859                    return Poll::Ready(Err(Error::Overrun));
860                }
861            }
862
863            if enable_idle_line_detection && sr.idle() {
864                // Idle line detected
865                return Poll::Ready(Ok(()));
866            }
867
868            Poll::Pending
869        });
870
871        // wait for the first of DMA request or idle line detected to completes
872        // select consumes its arguments
873        // when transfer is dropped, it will stop the DMA request
874        let r = match select(transfer, abort).await {
875            // DMA transfer completed first
876            Either::Left(((), _)) => Ok(ReadCompletionEvent::DmaCompleted),
877
878            // Idle line detected first
879            Either::Right((Ok(()), transfer)) => Ok(ReadCompletionEvent::Idle(
880                buffer_len - transfer.get_remaining_transfers() as usize,
881            )),
882
883            // error occurred
884            Either::Right((Err(e), _)) => Err(e),
885        };
886
887        drop(on_drop);
888
889        r
890    }
891
892    async fn inner_read(&mut self, buffer: &mut [u8], enable_idle_line_detection: bool) -> Result<usize, Error> {
893        if buffer.is_empty() {
894            return Ok(0);
895        } else if buffer.len() > 0xFFFF {
896            return Err(Error::BufferTooLong);
897        }
898
899        let buffer_len = buffer.len();
900
901        // wait for DMA to complete or IDLE line detection if requested
902        let res = self.inner_read_run(buffer, enable_idle_line_detection).await;
903
904        match res {
905            Ok(ReadCompletionEvent::DmaCompleted) => Ok(buffer_len),
906            Ok(ReadCompletionEvent::Idle(n)) => Ok(n),
907            Err(e) => Err(e),
908        }
909    }
910}
911
912impl<'d> UartRx<'d, Blocking> {
913    /// Create a new rx-only UART with no hardware flow control.
914    ///
915    /// Useful if you only want Uart Rx. It saves 1 pin and consumes a little less power.
916    pub fn new_blocking<T: Instance>(
917        peri: Peri<'d, T>,
918        rx: Peri<'d, impl RxPin<T>>,
919        config: Config,
920    ) -> Result<Self, ConfigError> {
921        Self::new_inner(peri, new_pin!(rx, config.rx_af()), None, None, config)
922    }
923
924    /// Create a new rx-only UART with a request-to-send pin
925    pub fn new_blocking_with_rts<T: Instance>(
926        peri: Peri<'d, T>,
927        rx: Peri<'d, impl RxPin<T>>,
928        rts: Peri<'d, impl RtsPin<T>>,
929        config: Config,
930    ) -> Result<Self, ConfigError> {
931        Self::new_inner(
932            peri,
933            new_pin!(rx, config.rx_af()),
934            new_pin!(rts, config.rts_config.af_type()),
935            None,
936            config,
937        )
938    }
939}
940
941impl<'d, M: Mode> UartRx<'d, M> {
942    fn new_inner<T: Instance>(
943        _peri: Peri<'d, T>,
944        rx: Option<Peri<'d, AnyPin>>,
945        rts: Option<Peri<'d, AnyPin>>,
946        rx_dma: Option<ChannelAndRequest<'d>>,
947        config: Config,
948    ) -> Result<Self, ConfigError> {
949        let mut this = Self {
950            _phantom: PhantomData,
951            info: T::info(),
952            state: T::state(),
953            kernel_clock: T::frequency(),
954            rx,
955            rts,
956            rx_dma,
957            detect_previous_overrun: config.detect_previous_overrun,
958            #[cfg(any(usart_v1, usart_v2))]
959            buffered_sr: regs::Sr(0),
960        };
961        this.enable_and_configure(&config)?;
962        Ok(this)
963    }
964
965    fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> {
966        let info = self.info;
967        let state = self.state;
968        state.tx_rx_refcount.store(1, Ordering::Relaxed);
969
970        info.rcc.enable_and_reset();
971
972        info.regs.cr3().write(|w| {
973            w.set_rtse(self.rts.is_some());
974        });
975        configure(info, self.kernel_clock, &config, true, false)?;
976
977        info.interrupt.unpend();
978        unsafe { info.interrupt.enable() };
979
980        Ok(())
981    }
982
983    /// Reconfigure the driver
984    pub fn set_config(&mut self, config: &Config) -> Result<(), ConfigError> {
985        reconfigure(self.info, self.kernel_clock, config)
986    }
987
988    #[cfg(any(usart_v1, usart_v2))]
989    fn check_rx_flags(&mut self) -> Result<bool, Error> {
990        let r = self.info.regs;
991        loop {
992            // Handle all buffered error flags.
993            if self.buffered_sr.pe() {
994                self.buffered_sr.set_pe(false);
995                return Err(Error::Parity);
996            } else if self.buffered_sr.fe() {
997                self.buffered_sr.set_fe(false);
998                return Err(Error::Framing);
999            } else if self.buffered_sr.ne() {
1000                self.buffered_sr.set_ne(false);
1001                return Err(Error::Noise);
1002            } else if self.buffered_sr.ore() {
1003                self.buffered_sr.set_ore(false);
1004                return Err(Error::Overrun);
1005            } else if self.buffered_sr.rxne() {
1006                self.buffered_sr.set_rxne(false);
1007                return Ok(true);
1008            } else {
1009                // No error flags from previous iterations were set: Check the actual status register
1010                let sr = r.sr().read();
1011                if !sr.rxne() {
1012                    return Ok(false);
1013                }
1014
1015                // Buffer the status register and let the loop handle the error flags.
1016                self.buffered_sr = sr;
1017            }
1018        }
1019    }
1020
1021    #[cfg(any(usart_v3, usart_v4))]
1022    fn check_rx_flags(&mut self) -> Result<bool, Error> {
1023        let r = self.info.regs;
1024        let sr = r.isr().read();
1025        if sr.pe() {
1026            r.icr().write(|w| w.set_pe(true));
1027            return Err(Error::Parity);
1028        } else if sr.fe() {
1029            r.icr().write(|w| w.set_fe(true));
1030            return Err(Error::Framing);
1031        } else if sr.ne() {
1032            r.icr().write(|w| w.set_ne(true));
1033            return Err(Error::Noise);
1034        } else if sr.ore() {
1035            r.icr().write(|w| w.set_ore(true));
1036            return Err(Error::Overrun);
1037        }
1038        Ok(sr.rxne())
1039    }
1040
1041    /// Read a single u8 if there is one available, otherwise return WouldBlock
1042    pub(crate) fn nb_read(&mut self) -> Result<u8, nb::Error<Error>> {
1043        let r = self.info.regs;
1044        if self.check_rx_flags()? {
1045            Ok(unsafe { rdr(r).read_volatile() })
1046        } else {
1047            Err(nb::Error::WouldBlock)
1048        }
1049    }
1050
1051    /// Perform a blocking read into `buffer`
1052    pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1053        let r = self.info.regs;
1054
1055        // Call flush for Half-Duplex mode if some bytes were written and flush was not called.
1056        // It prevents reading of bytes which have just been written.
1057        if r.cr3().read().hdsel() && r.cr1().read().te() {
1058            blocking_flush(self.info)?;
1059
1060            // Disable Transmitter and enable Receiver after flush
1061            r.cr1().modify(|reg| {
1062                reg.set_re(true);
1063                reg.set_te(false);
1064            });
1065        }
1066
1067        for b in buffer {
1068            while !self.check_rx_flags()? {}
1069            unsafe { *b = rdr(r).read_volatile() }
1070        }
1071        Ok(())
1072    }
1073
1074    /// Set baudrate
1075    pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
1076        set_baudrate(self.info, self.kernel_clock, baudrate)
1077    }
1078}
1079
1080impl<'d, M: Mode> Drop for UartTx<'d, M> {
1081    fn drop(&mut self) {
1082        self.tx.as_ref().map(|x| x.set_as_disconnected());
1083        self.cts.as_ref().map(|x| x.set_as_disconnected());
1084        self.de.as_ref().map(|x| x.set_as_disconnected());
1085        drop_tx_rx(self.info, self.state);
1086    }
1087}
1088
1089impl<'d, M: Mode> Drop for UartRx<'d, M> {
1090    fn drop(&mut self) {
1091        self.rx.as_ref().map(|x| x.set_as_disconnected());
1092        self.rts.as_ref().map(|x| x.set_as_disconnected());
1093        drop_tx_rx(self.info, self.state);
1094    }
1095}
1096
1097fn drop_tx_rx(info: &Info, state: &State) {
1098    // We cannot use atomic subtraction here, because it's not supported for all targets
1099    let is_last_drop = critical_section::with(|_| {
1100        let refcount = state.tx_rx_refcount.load(Ordering::Relaxed);
1101        assert!(refcount >= 1);
1102        state.tx_rx_refcount.store(refcount - 1, Ordering::Relaxed);
1103        refcount == 1
1104    });
1105    if is_last_drop {
1106        info.rcc.disable();
1107    }
1108}
1109
1110impl<'d> Uart<'d, Async> {
1111    /// Create a new bidirectional UART
1112    pub fn new<T: Instance>(
1113        peri: Peri<'d, T>,
1114        rx: Peri<'d, impl RxPin<T>>,
1115        tx: Peri<'d, impl TxPin<T>>,
1116        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1117        tx_dma: Peri<'d, impl TxDma<T>>,
1118        rx_dma: Peri<'d, impl RxDma<T>>,
1119        config: Config,
1120    ) -> Result<Self, ConfigError> {
1121        Self::new_inner(
1122            peri,
1123            new_pin!(rx, config.rx_af()),
1124            new_pin!(tx, config.tx_af()),
1125            None,
1126            None,
1127            None,
1128            new_dma!(tx_dma),
1129            new_dma!(rx_dma),
1130            config,
1131        )
1132    }
1133
1134    /// Create a new bidirectional UART with request-to-send and clear-to-send pins
1135    pub fn new_with_rtscts<T: Instance>(
1136        peri: Peri<'d, T>,
1137        rx: Peri<'d, impl RxPin<T>>,
1138        tx: Peri<'d, impl TxPin<T>>,
1139        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1140        rts: Peri<'d, impl RtsPin<T>>,
1141        cts: Peri<'d, impl CtsPin<T>>,
1142        tx_dma: Peri<'d, impl TxDma<T>>,
1143        rx_dma: Peri<'d, impl RxDma<T>>,
1144        config: Config,
1145    ) -> Result<Self, ConfigError> {
1146        Self::new_inner(
1147            peri,
1148            new_pin!(rx, config.rx_af()),
1149            new_pin!(tx, config.tx_af()),
1150            new_pin!(rts, config.rts_config.af_type()),
1151            new_pin!(cts, AfType::input(config.cts_pull)),
1152            None,
1153            new_dma!(tx_dma),
1154            new_dma!(rx_dma),
1155            config,
1156        )
1157    }
1158
1159    #[cfg(not(any(usart_v1, usart_v2)))]
1160    /// Create a new bidirectional UART with a driver-enable pin
1161    pub fn new_with_de<T: Instance>(
1162        peri: Peri<'d, T>,
1163        rx: Peri<'d, impl RxPin<T>>,
1164        tx: Peri<'d, impl TxPin<T>>,
1165        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1166        de: Peri<'d, impl DePin<T>>,
1167        tx_dma: Peri<'d, impl TxDma<T>>,
1168        rx_dma: Peri<'d, impl RxDma<T>>,
1169        config: Config,
1170    ) -> Result<Self, ConfigError> {
1171        Self::new_inner(
1172            peri,
1173            new_pin!(rx, config.rx_af()),
1174            new_pin!(tx, config.tx_af()),
1175            None,
1176            None,
1177            new_pin!(de, config.de_config.af_type()),
1178            new_dma!(tx_dma),
1179            new_dma!(rx_dma),
1180            config,
1181        )
1182    }
1183
1184    /// Create a single-wire half-duplex Uart transceiver on a single Tx pin.
1185    ///
1186    /// See [`new_half_duplex_on_rx`][`Self::new_half_duplex_on_rx`] if you would prefer to use an Rx pin
1187    /// (when it is available for your chip). There is no functional difference between these methods, as both
1188    /// allow bidirectional communication.
1189    ///
1190    /// The TX pin is always released when no data is transmitted. Thus, it acts as a standard
1191    /// I/O in idle or in reception. It means that the I/O must be configured so that TX is
1192    /// configured as alternate function open-drain with an external pull-up
1193    /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict
1194    /// on the line must be managed by software (for instance by using a centralized arbiter).
1195    #[doc(alias("HDSEL"))]
1196    pub fn new_half_duplex<T: Instance>(
1197        peri: Peri<'d, T>,
1198        tx: Peri<'d, impl TxPin<T>>,
1199        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1200        tx_dma: Peri<'d, impl TxDma<T>>,
1201        rx_dma: Peri<'d, impl RxDma<T>>,
1202        mut config: Config,
1203        readback: HalfDuplexReadback,
1204    ) -> Result<Self, ConfigError> {
1205        #[cfg(not(any(usart_v1, usart_v2)))]
1206        {
1207            config.swap_rx_tx = false;
1208        }
1209        config.duplex = Duplex::Half(readback);
1210
1211        Self::new_inner(
1212            peri,
1213            None,
1214            new_pin!(tx, config.tx_af()),
1215            None,
1216            None,
1217            None,
1218            new_dma!(tx_dma),
1219            new_dma!(rx_dma),
1220            config,
1221        )
1222    }
1223
1224    /// Create a single-wire half-duplex Uart transceiver on a single Rx pin.
1225    ///
1226    /// See [`new_half_duplex`][`Self::new_half_duplex`] if you would prefer to use an Tx pin.
1227    /// There is no functional difference between these methods, as both allow bidirectional communication.
1228    ///
1229    /// The pin is always released when no data is transmitted. Thus, it acts as a standard
1230    /// I/O in idle or in reception.
1231    /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict
1232    /// on the line must be managed by software (for instance by using a centralized arbiter).
1233    #[cfg(not(any(usart_v1, usart_v2)))]
1234    #[doc(alias("HDSEL"))]
1235    pub fn new_half_duplex_on_rx<T: Instance>(
1236        peri: Peri<'d, T>,
1237        rx: Peri<'d, impl RxPin<T>>,
1238        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
1239        tx_dma: Peri<'d, impl TxDma<T>>,
1240        rx_dma: Peri<'d, impl RxDma<T>>,
1241        mut config: Config,
1242        readback: HalfDuplexReadback,
1243    ) -> Result<Self, ConfigError> {
1244        config.swap_rx_tx = true;
1245        config.duplex = Duplex::Half(readback);
1246
1247        Self::new_inner(
1248            peri,
1249            None,
1250            None,
1251            new_pin!(rx, config.rx_af()),
1252            None,
1253            None,
1254            new_dma!(tx_dma),
1255            new_dma!(rx_dma),
1256            config,
1257        )
1258    }
1259
1260    /// Perform an asynchronous write
1261    pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
1262        self.tx.write(buffer).await
1263    }
1264
1265    /// Wait until transmission complete
1266    pub async fn flush(&mut self) -> Result<(), Error> {
1267        self.tx.flush().await
1268    }
1269
1270    /// Perform an asynchronous read into `buffer`
1271    pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1272        self.rx.read(buffer).await
1273    }
1274
1275    /// Perform an an asynchronous read with idle line detection enabled
1276    pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
1277        self.rx.read_until_idle(buffer).await
1278    }
1279}
1280
1281impl<'d> Uart<'d, Blocking> {
1282    /// Create a new blocking bidirectional UART.
1283    pub fn new_blocking<T: Instance>(
1284        peri: Peri<'d, T>,
1285        rx: Peri<'d, impl RxPin<T>>,
1286        tx: Peri<'d, impl TxPin<T>>,
1287        config: Config,
1288    ) -> Result<Self, ConfigError> {
1289        Self::new_inner(
1290            peri,
1291            new_pin!(rx, config.rx_af()),
1292            new_pin!(tx, config.tx_af()),
1293            None,
1294            None,
1295            None,
1296            None,
1297            None,
1298            config,
1299        )
1300    }
1301
1302    /// Create a new bidirectional UART with request-to-send and clear-to-send pins
1303    pub fn new_blocking_with_rtscts<T: Instance>(
1304        peri: Peri<'d, T>,
1305        rx: Peri<'d, impl RxPin<T>>,
1306        tx: Peri<'d, impl TxPin<T>>,
1307        rts: Peri<'d, impl RtsPin<T>>,
1308        cts: Peri<'d, impl CtsPin<T>>,
1309        config: Config,
1310    ) -> Result<Self, ConfigError> {
1311        Self::new_inner(
1312            peri,
1313            new_pin!(rx, config.rx_af()),
1314            new_pin!(tx, config.tx_af()),
1315            new_pin!(rts, config.rts_config.af_type()),
1316            new_pin!(cts, AfType::input(config.cts_pull)),
1317            None,
1318            None,
1319            None,
1320            config,
1321        )
1322    }
1323
1324    #[cfg(not(any(usart_v1, usart_v2)))]
1325    /// Create a new bidirectional UART with a driver-enable pin
1326    pub fn new_blocking_with_de<T: Instance>(
1327        peri: Peri<'d, T>,
1328        rx: Peri<'d, impl RxPin<T>>,
1329        tx: Peri<'d, impl TxPin<T>>,
1330        de: Peri<'d, impl DePin<T>>,
1331        config: Config,
1332    ) -> Result<Self, ConfigError> {
1333        Self::new_inner(
1334            peri,
1335            new_pin!(rx, config.rx_af()),
1336            new_pin!(tx, config.tx_af()),
1337            None,
1338            None,
1339            new_pin!(de, config.de_config.af_type()),
1340            None,
1341            None,
1342            config,
1343        )
1344    }
1345
1346    /// Create a single-wire half-duplex Uart transceiver on a single Tx pin.
1347    ///
1348    /// See [`new_half_duplex_on_rx`][`Self::new_half_duplex_on_rx`] if you would prefer to use an Rx pin
1349    /// (when it is available for your chip). There is no functional difference between these methods, as both
1350    /// allow bidirectional communication.
1351    ///
1352    /// The pin is always released when no data is transmitted. Thus, it acts as a standard
1353    /// I/O in idle or in reception.
1354    /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict
1355    /// on the line must be managed by software (for instance by using a centralized arbiter).
1356    #[doc(alias("HDSEL"))]
1357    pub fn new_blocking_half_duplex<T: Instance>(
1358        peri: Peri<'d, T>,
1359        tx: Peri<'d, impl TxPin<T>>,
1360        mut config: Config,
1361        readback: HalfDuplexReadback,
1362    ) -> Result<Self, ConfigError> {
1363        #[cfg(not(any(usart_v1, usart_v2)))]
1364        {
1365            config.swap_rx_tx = false;
1366        }
1367        config.duplex = Duplex::Half(readback);
1368
1369        Self::new_inner(
1370            peri,
1371            None,
1372            new_pin!(tx, config.tx_af()),
1373            None,
1374            None,
1375            None,
1376            None,
1377            None,
1378            config,
1379        )
1380    }
1381
1382    /// Create a single-wire half-duplex Uart transceiver on a single Rx pin.
1383    ///
1384    /// See [`new_half_duplex`][`Self::new_half_duplex`] if you would prefer to use an Tx pin.
1385    /// There is no functional difference between these methods, as both allow bidirectional communication.
1386    ///
1387    /// The pin is always released when no data is transmitted. Thus, it acts as a standard
1388    /// I/O in idle or in reception.
1389    /// Apart from this, the communication protocol is similar to normal USART mode. Any conflict
1390    /// on the line must be managed by software (for instance by using a centralized arbiter).
1391    #[cfg(not(any(usart_v1, usart_v2)))]
1392    #[doc(alias("HDSEL"))]
1393    pub fn new_blocking_half_duplex_on_rx<T: Instance>(
1394        peri: Peri<'d, T>,
1395        rx: Peri<'d, impl RxPin<T>>,
1396        mut config: Config,
1397        readback: HalfDuplexReadback,
1398    ) -> Result<Self, ConfigError> {
1399        config.swap_rx_tx = true;
1400        config.duplex = Duplex::Half(readback);
1401
1402        Self::new_inner(
1403            peri,
1404            None,
1405            None,
1406            new_pin!(rx, config.rx_af()),
1407            None,
1408            None,
1409            None,
1410            None,
1411            config,
1412        )
1413    }
1414}
1415
1416impl<'d, M: Mode> Uart<'d, M> {
1417    fn new_inner<T: Instance>(
1418        _peri: Peri<'d, T>,
1419        rx: Option<Peri<'d, AnyPin>>,
1420        tx: Option<Peri<'d, AnyPin>>,
1421        rts: Option<Peri<'d, AnyPin>>,
1422        cts: Option<Peri<'d, AnyPin>>,
1423        de: Option<Peri<'d, AnyPin>>,
1424        tx_dma: Option<ChannelAndRequest<'d>>,
1425        rx_dma: Option<ChannelAndRequest<'d>>,
1426        config: Config,
1427    ) -> Result<Self, ConfigError> {
1428        let info = T::info();
1429        let state = T::state();
1430        let kernel_clock = T::frequency();
1431
1432        let mut this = Self {
1433            tx: UartTx {
1434                _phantom: PhantomData,
1435                info,
1436                state,
1437                kernel_clock,
1438                tx,
1439                cts,
1440                de,
1441                tx_dma,
1442                duplex: config.duplex,
1443            },
1444            rx: UartRx {
1445                _phantom: PhantomData,
1446                info,
1447                state,
1448                kernel_clock,
1449                rx,
1450                rts,
1451                rx_dma,
1452                detect_previous_overrun: config.detect_previous_overrun,
1453                #[cfg(any(usart_v1, usart_v2))]
1454                buffered_sr: regs::Sr(0),
1455            },
1456        };
1457        this.enable_and_configure(&config)?;
1458        Ok(this)
1459    }
1460
1461    fn enable_and_configure(&mut self, config: &Config) -> Result<(), ConfigError> {
1462        let info = self.rx.info;
1463        let state = self.rx.state;
1464        state.tx_rx_refcount.store(2, Ordering::Relaxed);
1465
1466        info.rcc.enable_and_reset();
1467
1468        info.regs.cr3().write(|w| {
1469            w.set_rtse(self.rx.rts.is_some());
1470            w.set_ctse(self.tx.cts.is_some());
1471            #[cfg(not(any(usart_v1, usart_v2)))]
1472            w.set_dem(self.tx.de.is_some());
1473        });
1474        configure(info, self.rx.kernel_clock, config, true, true)?;
1475
1476        info.interrupt.unpend();
1477        unsafe { info.interrupt.enable() };
1478
1479        Ok(())
1480    }
1481
1482    /// Perform a blocking write
1483    pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
1484        self.tx.blocking_write(buffer)
1485    }
1486
1487    /// Block until transmission complete
1488    pub fn blocking_flush(&mut self) -> Result<(), Error> {
1489        self.tx.blocking_flush()
1490    }
1491
1492    /// Read a single `u8` or return `WouldBlock`
1493    pub(crate) fn nb_read(&mut self) -> Result<u8, nb::Error<Error>> {
1494        self.rx.nb_read()
1495    }
1496
1497    /// Perform a blocking read into `buffer`
1498    pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
1499        self.rx.blocking_read(buffer)
1500    }
1501
1502    /// Split the Uart into a transmitter and receiver, which is
1503    /// particularly useful when having two tasks correlating to
1504    /// transmitting and receiving.
1505    pub fn split(self) -> (UartTx<'d, M>, UartRx<'d, M>) {
1506        (self.tx, self.rx)
1507    }
1508
1509    /// Split the Uart into a transmitter and receiver by mutable reference,
1510    /// which is particularly useful when having two tasks correlating to
1511    /// transmitting and receiving.
1512    pub fn split_ref(&mut self) -> (&mut UartTx<'d, M>, &mut UartRx<'d, M>) {
1513        (&mut self.tx, &mut self.rx)
1514    }
1515
1516    /// Send break character
1517    pub fn send_break(&self) {
1518        self.tx.send_break();
1519    }
1520
1521    /// Set baudrate
1522    pub fn set_baudrate(&self, baudrate: u32) -> Result<(), ConfigError> {
1523        self.tx.set_baudrate(baudrate)?;
1524        self.rx.set_baudrate(baudrate)?;
1525        Ok(())
1526    }
1527}
1528
1529fn reconfigure(info: &Info, kernel_clock: Hertz, config: &Config) -> Result<(), ConfigError> {
1530    info.interrupt.disable();
1531    let r = info.regs;
1532
1533    let cr = r.cr1().read();
1534    configure(info, kernel_clock, config, cr.re(), cr.te())?;
1535
1536    info.interrupt.unpend();
1537    unsafe { info.interrupt.enable() };
1538
1539    Ok(())
1540}
1541
1542fn calculate_brr(baud: u32, pclk: u32, presc: u32, mul: u32) -> u32 {
1543    // The calculation to be done to get the BRR is `mul * pclk / presc / baud`
1544    // To do this in 32-bit only we can't multiply `mul` and `pclk`
1545    let clock = pclk / presc;
1546
1547    // The mul is applied as the last operation to prevent overflow
1548    let brr = clock / baud * mul;
1549
1550    // The BRR calculation will be a bit off because of integer rounding.
1551    // Because we multiplied our inaccuracy with mul, our rounding now needs to be in proportion to mul.
1552    let rounding = ((clock % baud) * mul + (baud / 2)) / baud;
1553
1554    brr + rounding
1555}
1556
1557fn set_baudrate(info: &Info, kernel_clock: Hertz, baudrate: u32) -> Result<(), ConfigError> {
1558    info.interrupt.disable();
1559
1560    set_usart_baudrate(info, kernel_clock, baudrate)?;
1561
1562    info.interrupt.unpend();
1563    unsafe { info.interrupt.enable() };
1564
1565    Ok(())
1566}
1567
1568fn find_and_set_brr(r: Regs, kind: Kind, kernel_clock: Hertz, baudrate: u32) -> Result<bool, ConfigError> {
1569    #[cfg(not(usart_v4))]
1570    static DIVS: [(u16, ()); 1] = [(1, ())];
1571
1572    #[cfg(usart_v4)]
1573    static DIVS: [(u16, vals::Presc); 12] = [
1574        (1, vals::Presc::DIV1),
1575        (2, vals::Presc::DIV2),
1576        (4, vals::Presc::DIV4),
1577        (6, vals::Presc::DIV6),
1578        (8, vals::Presc::DIV8),
1579        (10, vals::Presc::DIV10),
1580        (12, vals::Presc::DIV12),
1581        (16, vals::Presc::DIV16),
1582        (32, vals::Presc::DIV32),
1583        (64, vals::Presc::DIV64),
1584        (128, vals::Presc::DIV128),
1585        (256, vals::Presc::DIV256),
1586    ];
1587
1588    let (mul, brr_min, brr_max) = match kind {
1589        #[cfg(any(usart_v3, usart_v4))]
1590        Kind::Lpuart => {
1591            trace!("USART: Kind::Lpuart");
1592            (256, 0x300, 0x10_0000)
1593        }
1594        Kind::Uart => {
1595            trace!("USART: Kind::Uart");
1596            (1, 0x10, 0x1_0000)
1597        }
1598    };
1599
1600    let mut found_brr = None;
1601    #[cfg(not(usart_v1))]
1602    let mut over8 = false;
1603    #[cfg(usart_v1)]
1604    let over8 = false;
1605
1606    for &(presc, _presc_val) in &DIVS {
1607        let brr = calculate_brr(baudrate, kernel_clock.0, presc as u32, mul);
1608        trace!(
1609            "USART: presc={}, div=0x{:08x} (mantissa = {}, fraction = {})",
1610            presc,
1611            brr,
1612            brr >> 4,
1613            brr & 0x0F
1614        );
1615
1616        if brr < brr_min {
1617            #[cfg(not(usart_v1))]
1618            if brr * 2 >= brr_min && kind == Kind::Uart && !cfg!(usart_v1) {
1619                over8 = true;
1620                r.brr().write_value(regs::Brr(((brr << 1) & !0xF) | (brr & 0x07)));
1621                #[cfg(usart_v4)]
1622                r.presc().write(|w| w.set_prescaler(_presc_val));
1623                found_brr = Some(brr);
1624                break;
1625            }
1626            return Err(ConfigError::BaudrateTooHigh);
1627        }
1628
1629        if brr < brr_max {
1630            r.brr().write_value(regs::Brr(brr));
1631            #[cfg(usart_v4)]
1632            r.presc().write(|w| w.set_prescaler(_presc_val));
1633            found_brr = Some(brr);
1634            break;
1635        }
1636    }
1637
1638    match found_brr {
1639        Some(brr) => {
1640            #[cfg(not(usart_v1))]
1641            let oversampling = if over8 { "8 bit" } else { "16 bit" };
1642            #[cfg(usart_v1)]
1643            let oversampling = "default";
1644            trace!(
1645                "Using {} oversampling, desired baudrate: {}, actual baudrate: {}",
1646                oversampling,
1647                baudrate,
1648                kernel_clock.0 / brr * mul
1649            );
1650            Ok(over8)
1651        }
1652        None => Err(ConfigError::BaudrateTooLow),
1653    }
1654}
1655
1656fn set_usart_baudrate(info: &Info, kernel_clock: Hertz, baudrate: u32) -> Result<(), ConfigError> {
1657    let r = info.regs;
1658    r.cr1().modify(|w| {
1659        // disable uart
1660        w.set_ue(false);
1661    });
1662
1663    #[cfg(not(usart_v1))]
1664    let over8 = find_and_set_brr(r, info.kind, kernel_clock, baudrate)?;
1665    #[cfg(usart_v1)]
1666    let _over8 = find_and_set_brr(r, info.kind, kernel_clock, baudrate)?;
1667
1668    r.cr1().modify(|w| {
1669        // enable uart
1670        w.set_ue(true);
1671
1672        #[cfg(not(usart_v1))]
1673        w.set_over8(vals::Over8::from_bits(over8 as _));
1674    });
1675
1676    Ok(())
1677}
1678
1679fn configure(
1680    info: &Info,
1681    kernel_clock: Hertz,
1682    config: &Config,
1683    enable_rx: bool,
1684    enable_tx: bool,
1685) -> Result<(), ConfigError> {
1686    let r = info.regs;
1687    let kind = info.kind;
1688
1689    if !enable_rx && !enable_tx {
1690        return Err(ConfigError::RxOrTxNotEnabled);
1691    }
1692
1693    // UART must be disabled during configuration.
1694    r.cr1().modify(|w| {
1695        w.set_ue(false);
1696    });
1697
1698    #[cfg(not(usart_v1))]
1699    let over8 = find_and_set_brr(r, kind, kernel_clock, config.baudrate)?;
1700    #[cfg(usart_v1)]
1701    let _over8 = find_and_set_brr(r, kind, kernel_clock, config.baudrate)?;
1702
1703    r.cr2().write(|w| {
1704        w.set_stop(match config.stop_bits {
1705            StopBits::STOP0P5 => vals::Stop::STOP0P5,
1706            StopBits::STOP1 => vals::Stop::STOP1,
1707            StopBits::STOP1P5 => vals::Stop::STOP1P5,
1708            StopBits::STOP2 => vals::Stop::STOP2,
1709        });
1710
1711        #[cfg(any(usart_v3, usart_v4))]
1712        {
1713            w.set_txinv(config.invert_tx);
1714            w.set_rxinv(config.invert_rx);
1715            w.set_swap(config.swap_rx_tx);
1716        }
1717    });
1718
1719    r.cr3().modify(|w| {
1720        #[cfg(not(usart_v1))]
1721        w.set_onebit(config.assume_noise_free);
1722        w.set_hdsel(config.duplex.is_half());
1723    });
1724
1725    r.cr1().write(|w| {
1726        // enable uart
1727        w.set_ue(true);
1728
1729        if config.duplex.is_half() {
1730            // The te and re bits will be set by write, read and flush methods.
1731            // Receiver should be enabled by default for Half-Duplex.
1732            w.set_te(false);
1733            w.set_re(true);
1734        } else {
1735            // enable transceiver
1736            w.set_te(enable_tx);
1737            // enable receiver
1738            w.set_re(enable_rx);
1739        }
1740
1741        // configure word size and parity, since the parity bit is inserted into the MSB position,
1742        // it increases the effective word size
1743        match (config.parity, config.data_bits) {
1744            (Parity::ParityNone, DataBits::DataBits8) => {
1745                trace!("USART: m0: 8 data bits, no parity");
1746                w.set_m0(vals::M0::BIT8);
1747                #[cfg(any(usart_v3, usart_v4))]
1748                w.set_m1(vals::M1::M0);
1749                w.set_pce(false);
1750            }
1751            (Parity::ParityNone, DataBits::DataBits9) => {
1752                trace!("USART: m0: 9 data bits, no parity");
1753                w.set_m0(vals::M0::BIT9);
1754                #[cfg(any(usart_v3, usart_v4))]
1755                w.set_m1(vals::M1::M0);
1756                w.set_pce(false);
1757            }
1758            #[cfg(any(usart_v3, usart_v4))]
1759            (Parity::ParityNone, DataBits::DataBits7) => {
1760                trace!("USART: m0: 7 data bits, no parity");
1761                w.set_m0(vals::M0::BIT8);
1762                w.set_m1(vals::M1::BIT7);
1763                w.set_pce(false);
1764            }
1765            (Parity::ParityEven, DataBits::DataBits8) => {
1766                trace!("USART: m0: 8 data bits, even parity");
1767                w.set_m0(vals::M0::BIT9);
1768                #[cfg(any(usart_v3, usart_v4))]
1769                w.set_m1(vals::M1::M0);
1770                w.set_pce(true);
1771                w.set_ps(vals::Ps::EVEN);
1772            }
1773            (Parity::ParityEven, DataBits::DataBits7) => {
1774                trace!("USART: m0: 7 data bits, even parity");
1775                w.set_m0(vals::M0::BIT8);
1776                #[cfg(any(usart_v3, usart_v4))]
1777                w.set_m1(vals::M1::M0);
1778                w.set_pce(true);
1779                w.set_ps(vals::Ps::EVEN);
1780            }
1781            (Parity::ParityOdd, DataBits::DataBits8) => {
1782                trace!("USART: m0: 8 data bits, odd parity");
1783                w.set_m0(vals::M0::BIT9);
1784                #[cfg(any(usart_v3, usart_v4))]
1785                w.set_m1(vals::M1::M0);
1786                w.set_pce(true);
1787                w.set_ps(vals::Ps::ODD);
1788            }
1789            (Parity::ParityOdd, DataBits::DataBits7) => {
1790                trace!("USART: m0: 7 data bits, odd parity");
1791                w.set_m0(vals::M0::BIT8);
1792                #[cfg(any(usart_v3, usart_v4))]
1793                w.set_m1(vals::M1::M0);
1794                w.set_pce(true);
1795                w.set_ps(vals::Ps::ODD);
1796            }
1797            _ => {
1798                return Err(ConfigError::DataParityNotSupported);
1799            }
1800        }
1801        #[cfg(not(usart_v1))]
1802        w.set_over8(vals::Over8::from_bits(over8 as _));
1803        #[cfg(usart_v4)]
1804        {
1805            trace!("USART: set_fifoen: true (usart_v4)");
1806            w.set_fifoen(true);
1807        }
1808
1809        Ok(())
1810    })?;
1811
1812    Ok(())
1813}
1814
1815impl<'d, M: Mode> embedded_hal_02::serial::Read<u8> for UartRx<'d, M> {
1816    type Error = Error;
1817    fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1818        self.nb_read()
1819    }
1820}
1821
1822impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write<u8> for UartTx<'d, M> {
1823    type Error = Error;
1824    fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> {
1825        self.blocking_write(buffer)
1826    }
1827    fn bflush(&mut self) -> Result<(), Self::Error> {
1828        self.blocking_flush()
1829    }
1830}
1831
1832impl<'d, M: Mode> embedded_hal_02::serial::Read<u8> for Uart<'d, M> {
1833    type Error = Error;
1834    fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1835        self.nb_read()
1836    }
1837}
1838
1839impl<'d, M: Mode> embedded_hal_02::blocking::serial::Write<u8> for Uart<'d, M> {
1840    type Error = Error;
1841    fn bwrite_all(&mut self, buffer: &[u8]) -> Result<(), Self::Error> {
1842        self.blocking_write(buffer)
1843    }
1844    fn bflush(&mut self) -> Result<(), Self::Error> {
1845        self.blocking_flush()
1846    }
1847}
1848
1849impl embedded_hal_nb::serial::Error for Error {
1850    fn kind(&self) -> embedded_hal_nb::serial::ErrorKind {
1851        match *self {
1852            Self::Framing => embedded_hal_nb::serial::ErrorKind::FrameFormat,
1853            Self::Noise => embedded_hal_nb::serial::ErrorKind::Noise,
1854            Self::Overrun => embedded_hal_nb::serial::ErrorKind::Overrun,
1855            Self::Parity => embedded_hal_nb::serial::ErrorKind::Parity,
1856            Self::BufferTooLong => embedded_hal_nb::serial::ErrorKind::Other,
1857        }
1858    }
1859}
1860
1861impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for Uart<'d, M> {
1862    type Error = Error;
1863}
1864
1865impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartTx<'d, M> {
1866    type Error = Error;
1867}
1868
1869impl<'d, M: Mode> embedded_hal_nb::serial::ErrorType for UartRx<'d, M> {
1870    type Error = Error;
1871}
1872
1873impl<'d, M: Mode> embedded_hal_nb::serial::Read for UartRx<'d, M> {
1874    fn read(&mut self) -> nb::Result<u8, Self::Error> {
1875        self.nb_read()
1876    }
1877}
1878
1879impl<'d, M: Mode> embedded_hal_nb::serial::Write for UartTx<'d, M> {
1880    fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1881        self.nb_write(char)
1882    }
1883
1884    fn flush(&mut self) -> nb::Result<(), Self::Error> {
1885        self.blocking_flush().map_err(nb::Error::Other)
1886    }
1887}
1888
1889impl<'d, M: Mode> embedded_hal_nb::serial::Read for Uart<'d, M> {
1890    fn read(&mut self) -> Result<u8, nb::Error<Self::Error>> {
1891        self.nb_read()
1892    }
1893}
1894
1895impl<'d, M: Mode> embedded_hal_nb::serial::Write for Uart<'d, M> {
1896    fn write(&mut self, char: u8) -> nb::Result<(), Self::Error> {
1897        self.blocking_write(&[char]).map_err(nb::Error::Other)
1898    }
1899
1900    fn flush(&mut self) -> nb::Result<(), Self::Error> {
1901        self.blocking_flush().map_err(nb::Error::Other)
1902    }
1903}
1904
1905impl embedded_io::Error for Error {
1906    fn kind(&self) -> embedded_io::ErrorKind {
1907        embedded_io::ErrorKind::Other
1908    }
1909}
1910
1911impl<M: Mode> embedded_io::ErrorType for Uart<'_, M> {
1912    type Error = Error;
1913}
1914
1915impl<M: Mode> embedded_io::ErrorType for UartTx<'_, M> {
1916    type Error = Error;
1917}
1918
1919impl<M: Mode> embedded_io::Write for Uart<'_, M> {
1920    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1921        self.blocking_write(buf)?;
1922        Ok(buf.len())
1923    }
1924
1925    fn flush(&mut self) -> Result<(), Self::Error> {
1926        self.blocking_flush()
1927    }
1928}
1929
1930impl<M: Mode> embedded_io::Write for UartTx<'_, M> {
1931    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1932        self.blocking_write(buf)?;
1933        Ok(buf.len())
1934    }
1935
1936    fn flush(&mut self) -> Result<(), Self::Error> {
1937        self.blocking_flush()
1938    }
1939}
1940
1941impl embedded_io_async::Write for Uart<'_, Async> {
1942    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1943        self.write(buf).await?;
1944        Ok(buf.len())
1945    }
1946
1947    async fn flush(&mut self) -> Result<(), Self::Error> {
1948        self.flush().await
1949    }
1950}
1951
1952impl embedded_io_async::Write for UartTx<'_, Async> {
1953    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
1954        self.write(buf).await?;
1955        Ok(buf.len())
1956    }
1957
1958    async fn flush(&mut self) -> Result<(), Self::Error> {
1959        self.flush().await
1960    }
1961}
1962
1963pub use buffered::*;
1964
1965pub use crate::usart::buffered::InterruptHandler as BufferedInterruptHandler;
1966mod buffered;
1967
1968#[cfg(not(gpdma))]
1969mod ringbuffered;
1970#[cfg(not(gpdma))]
1971pub use ringbuffered::RingBufferedUartRx;
1972
1973#[cfg(any(usart_v1, usart_v2))]
1974fn tdr(r: crate::pac::usart::Usart) -> *mut u8 {
1975    r.dr().as_ptr() as _
1976}
1977
1978#[cfg(any(usart_v1, usart_v2))]
1979fn rdr(r: crate::pac::usart::Usart) -> *mut u8 {
1980    r.dr().as_ptr() as _
1981}
1982
1983#[cfg(any(usart_v1, usart_v2))]
1984fn sr(r: crate::pac::usart::Usart) -> crate::pac::common::Reg<regs::Sr, crate::pac::common::RW> {
1985    r.sr()
1986}
1987
1988#[cfg(any(usart_v1, usart_v2))]
1989#[allow(unused)]
1990fn clear_interrupt_flags(_r: Regs, _sr: regs::Sr) {
1991    // On v1 the flags are cleared implicitly by reads and writes to DR.
1992}
1993
1994#[cfg(any(usart_v3, usart_v4))]
1995fn tdr(r: Regs) -> *mut u8 {
1996    r.tdr().as_ptr() as _
1997}
1998
1999#[cfg(any(usart_v3, usart_v4))]
2000fn rdr(r: Regs) -> *mut u8 {
2001    r.rdr().as_ptr() as _
2002}
2003
2004#[cfg(any(usart_v3, usart_v4))]
2005fn sr(r: Regs) -> crate::pac::common::Reg<regs::Isr, crate::pac::common::R> {
2006    r.isr()
2007}
2008
2009#[cfg(any(usart_v3, usart_v4))]
2010#[allow(unused)]
2011fn clear_interrupt_flags(r: Regs, sr: regs::Isr) {
2012    r.icr().write(|w| *w = regs::Icr(sr.0));
2013}
2014
2015#[derive(Clone, Copy, PartialEq, Eq)]
2016enum Kind {
2017    Uart,
2018    #[cfg(any(usart_v3, usart_v4))]
2019    #[allow(unused)]
2020    Lpuart,
2021}
2022
2023struct State {
2024    rx_waker: AtomicWaker,
2025    tx_waker: AtomicWaker,
2026    tx_rx_refcount: AtomicU8,
2027}
2028
2029impl State {
2030    const fn new() -> Self {
2031        Self {
2032            rx_waker: AtomicWaker::new(),
2033            tx_waker: AtomicWaker::new(),
2034            tx_rx_refcount: AtomicU8::new(0),
2035        }
2036    }
2037}
2038
2039struct Info {
2040    regs: Regs,
2041    rcc: RccInfo,
2042    interrupt: Interrupt,
2043    kind: Kind,
2044}
2045
2046#[allow(private_interfaces)]
2047pub(crate) trait SealedInstance: crate::rcc::RccPeripheral {
2048    fn info() -> &'static Info;
2049    fn state() -> &'static State;
2050    fn buffered_state() -> &'static buffered::State;
2051}
2052
2053/// USART peripheral instance trait.
2054#[allow(private_bounds)]
2055pub trait Instance: SealedInstance + PeripheralType + 'static + Send {
2056    /// Interrupt for this peripheral.
2057    type Interrupt: interrupt::typelevel::Interrupt;
2058}
2059
2060pin_trait!(RxPin, Instance);
2061pin_trait!(TxPin, Instance);
2062pin_trait!(CtsPin, Instance);
2063pin_trait!(RtsPin, Instance);
2064pin_trait!(CkPin, Instance);
2065pin_trait!(DePin, Instance);
2066
2067dma_trait!(TxDma, Instance);
2068dma_trait!(RxDma, Instance);
2069
2070macro_rules! impl_usart {
2071    ($inst:ident, $irq:ident, $kind:expr) => {
2072        #[allow(private_interfaces)]
2073        impl SealedInstance for crate::peripherals::$inst {
2074            fn info() -> &'static Info {
2075                static INFO: Info = Info {
2076                    regs: unsafe { Regs::from_ptr(crate::pac::$inst.as_ptr()) },
2077                    rcc: crate::peripherals::$inst::RCC_INFO,
2078                    interrupt: crate::interrupt::typelevel::$irq::IRQ,
2079                    kind: $kind,
2080                };
2081                &INFO
2082            }
2083
2084            fn state() -> &'static State {
2085                static STATE: State = State::new();
2086                &STATE
2087            }
2088
2089            fn buffered_state() -> &'static buffered::State {
2090                static BUFFERED_STATE: buffered::State = buffered::State::new();
2091                &BUFFERED_STATE
2092            }
2093        }
2094
2095        impl Instance for crate::peripherals::$inst {
2096            type Interrupt = crate::interrupt::typelevel::$irq;
2097        }
2098    };
2099}
2100
2101foreach_interrupt!(
2102    ($inst:ident, usart, LPUART, $signal_name:ident, $irq:ident) => {
2103        impl_usart!($inst, $irq, Kind::Lpuart);
2104    };
2105    ($inst:ident, usart, $block:ident, $signal_name:ident, $irq:ident) => {
2106        impl_usart!($inst, $irq, Kind::Uart);
2107    };
2108);