Skip to main content

esp_hal/uart/
mod.rs

1//! # Universal Asynchronous Receiver/Transmitter (UART)
2//!
3//! ## Overview
4//!
5//! The UART is a hardware peripheral which handles communication using serial
6//! communication interfaces, such as RS232 and RS485. This peripheral provides!
7//! a cheap and ubiquitous method for full- and half-duplex communication
8//! between devices.
9//!
10//! Depending on your device, two or more UART controllers are available for
11//! use, all of which can be configured and used in the same way. All UART
12//! controllers are compatible with UART-enabled devices from various
13//! manufacturers, and can also support Infrared Data Association (IrDA)
14//! protocols.
15//!
16//! ## Configuration
17//!
18//! Each UART controller is individually configurable, and the usual setting
19//! such as baud rate, data bits, parity, and stop bits can easily be
20//! configured. Additionally, the receive (RX) and transmit (TX) pins need to
21//! be specified.
22//!
23//! The UART controller can be configured to invert the polarity of the pins.
24//! This is achieved by inverting the desired pins, and then constructing the
25//! UART instance using the inverted pins.
26//!
27//! ## Usage
28//!
29//! The UART driver implements a number of third-party traits, with the
30//! intention of making the HAL inter-compatible with various device drivers
31//! from the community. This includes, but is not limited to, the [embedded-hal]
32//! and [embedded-io] blocking traits, and the [embedded-hal-async] and
33//! [embedded-io-async] asynchronous traits.
34//!
35//! In addition to the interfaces provided by these traits, native APIs are also
36//! available. See the examples below for more information on how to interact
37//! with this driver.
38//!
39//! [embedded-hal]: embedded_hal
40//! [embedded-io]: embedded_io_07
41//! [embedded-hal-async]: embedded_hal_async
42//! [embedded-io-async]: embedded_io_async_07
43
44crate::unstable_driver! {
45    #[cfg(uhci_driver_supported)]
46    pub mod uhci;
47
48    #[cfg(lp_uart_driver_supported)]
49    pub mod lp_uart;
50}
51
52#[cfg_attr(uart_version = "1", path = "clocks/v1.rs")]
53#[cfg_attr(soc_has_pcr, path = "clocks/v2_pcr.rs")]
54#[cfg_attr(esp32p4, path = "clocks/v2_esp32p4.rs")]
55#[cfg_attr(esp32s31, path = "clocks/v2_esp32s31.rs")]
56mod clocks;
57
58mod compat;
59mod low_level;
60
61use core::{marker::PhantomData, mem::DropGuard, sync::atomic::Ordering};
62
63use embedded_hal_async::delay::DelayNs;
64use enumset::{EnumSet, EnumSetType};
65pub use low_level::Instance;
66use low_level::{
67    Info,
68    RxEvent,
69    State,
70    TxEvent,
71    UartClockGuard,
72    UartRxFuture,
73    UartTxFuture,
74    enable_register_sync,
75    rx_event_check_for_error,
76    sync_regs,
77};
78
79use crate::{
80    Async,
81    Blocking,
82    DriverMode,
83    gpio::{
84        InputConfig,
85        OutputConfig,
86        PinGuard,
87        Pull,
88        interconnect::{PeripheralInput, PeripheralOutput},
89    },
90    interrupt::InterruptHandler,
91    pac::uart0::RegisterBlock,
92    rtc_cntl::WakeLock,
93};
94
95crate::any_peripheral! {
96    /// Any UART peripheral.
97    pub peripheral AnyUart<'d> {
98        #[cfg(soc_has_uart0)]
99        Uart0(crate::peripherals::UART0<'d>),
100        #[cfg(soc_has_uart1)]
101        Uart1(crate::peripherals::UART1<'d>),
102        #[cfg(soc_has_uart2)]
103        Uart2(crate::peripherals::UART2<'d>),
104        #[cfg(soc_has_uart3)]
105        Uart3(crate::peripherals::UART3<'d>),
106        #[cfg(soc_has_uart4)]
107        Uart4(crate::peripherals::UART4<'d>),
108    }
109}
110
111impl Instance for AnyUart<'_> {
112    #[inline]
113    fn parts(&self) -> (&'static Info, &'static State) {
114        any::delegate!(self, uart => { uart.parts() })
115    }
116}
117
118impl AnyUart<'_> {
119    pub(super) fn bind_peri_interrupt(&self, handler: InterruptHandler) {
120        any::delegate!(self, uart => { uart.bind_peri_interrupt(handler) })
121    }
122
123    pub(super) fn disable_peri_interrupt_on_all_cores(&self) {
124        any::delegate!(self, uart => { uart.disable_peri_interrupt_on_all_cores() })
125    }
126
127    pub(super) fn set_interrupt_handler(&self, handler: InterruptHandler) {
128        self.disable_peri_interrupt_on_all_cores();
129
130        self.info().enable_listen(EnumSet::all(), false);
131        self.info().clear_interrupts(EnumSet::all());
132
133        self.bind_peri_interrupt(handler);
134    }
135}
136
137/// UART RX Error
138#[derive(Debug, Clone, Copy, PartialEq)]
139#[cfg_attr(feature = "defmt", derive(defmt::Format))]
140#[non_exhaustive]
141pub enum RxError {
142    /// An RX FIFO overflow happened.
143    ///
144    /// Occurs when the RX FIFO is full and a new byte is received. The RX FIFO
145    /// is then automatically reset by the driver.
146    FifoOverflowed,
147
148    /// A glitch was detected on the RX line.
149    ///
150    /// Occurs when an unexpected or erroneous signal (glitch) is detected on the
151    /// UART RX line, which could lead to incorrect data reception.
152    GlitchOccurred,
153
154    /// A framing error was detected on the RX line.
155    ///
156    /// Occurs when the received data does not conform to the expected UART frame
157    /// format.
158    FrameFormatViolated,
159
160    /// A parity error was detected on the RX line.
161    ///
162    /// Occurs when the parity bit in the received data does not match the
163    /// expected parity configuration.
164    ParityMismatch,
165}
166
167impl core::error::Error for RxError {}
168
169/// UART RX error conditions that can be reported by read operations.
170///
171/// Used with [`RxConfig::with_reported_errors`] to choose which hardware RX
172/// error conditions should make read operations return an [`RxError`]
173#[derive(Debug, EnumSetType)]
174#[cfg_attr(feature = "defmt", derive(defmt::Format))]
175#[instability::unstable]
176#[non_exhaustive]
177pub enum RxErrorKind {
178    /// An RX FIFO overflow happened.
179    FifoOverflowed,
180    /// A glitch was detected on the RX line.
181    GlitchOccurred,
182    /// A framing error was detected on the RX line.
183    FrameFormatViolated,
184    /// A parity error was detected on the RX line.
185    ParityMismatch,
186}
187
188impl From<RxErrorKind> for RxError {
189    fn from(value: RxErrorKind) -> Self {
190        match value {
191            RxErrorKind::FifoOverflowed => RxError::FifoOverflowed,
192            RxErrorKind::GlitchOccurred => RxError::GlitchOccurred,
193            RxErrorKind::FrameFormatViolated => RxError::FrameFormatViolated,
194            RxErrorKind::ParityMismatch => RxError::ParityMismatch,
195        }
196    }
197}
198
199impl core::fmt::Display for RxError {
200    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
201        match self {
202            RxError::FifoOverflowed => write!(f, "The RX FIFO overflowed"),
203            RxError::GlitchOccurred => write!(f, "A glitch was detected on the RX line"),
204            RxError::FrameFormatViolated => {
205                write!(f, "A framing error was detected on the RX line")
206            }
207            RxError::ParityMismatch => write!(f, "A parity error was detected on the RX line"),
208        }
209    }
210}
211
212/// UART TX Error
213#[derive(Debug, Clone, Copy, PartialEq)]
214#[cfg_attr(feature = "defmt", derive(defmt::Format))]
215#[non_exhaustive]
216pub enum TxError {}
217
218impl core::fmt::Display for TxError {
219    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
220        write!(f, "Tx error")
221    }
222}
223
224impl core::error::Error for TxError {}
225
226#[instability::unstable]
227pub use crate::soc::clocks::UartFunctionClockSclk as ClockSource;
228
229/// Number of data bits
230///
231/// Configurations for the number of data bits used in UART communication. The
232/// number of data bits defines the length of each transmitted or received data
233/// frame.
234#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
235#[cfg_attr(feature = "defmt", derive(defmt::Format))]
236pub enum DataBits {
237    /// 5 data bits per frame.
238    _5,
239    /// 6 data bits per frame.
240    _6,
241    /// 7 data bits per frame.
242    _7,
243    /// 8 data bits per frame.
244    #[default]
245    _8,
246}
247
248/// Parity check
249///
250/// Parity is a form of error detection in UART communication, used to
251/// ensure that the data has not been corrupted during transmission. The
252/// parity bit is added to the data bits to make the number of 1-bits
253/// either even or odd.
254#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
255#[cfg_attr(feature = "defmt", derive(defmt::Format))]
256pub enum Parity {
257    /// No parity bit is used.
258    #[default]
259    None,
260    /// Even parity: the parity bit is set to make the total number of
261    /// 1-bits even.
262    Even,
263    /// Odd parity: the parity bit is set to make the total number of 1-bits
264    /// odd.
265    Odd,
266}
267
268/// Number of stop bits
269///
270/// The stop bit(s) signal the end of a data packet in UART communication.
271/// Possible configurations for the number of stop bits.
272#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
273#[cfg_attr(feature = "defmt", derive(defmt::Format))]
274pub enum StopBits {
275    /// 1 stop bit.
276    #[default]
277    _1,
278    /// 1.5 stop bits.
279    _1p5,
280    /// 2 stop bits.
281    _2,
282}
283
284/// Software flow control settings.
285#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
286#[cfg_attr(feature = "defmt", derive(defmt::Format))]
287#[instability::unstable]
288pub enum SwFlowControl {
289    #[default]
290    /// Disables software flow control.
291    Disabled,
292    /// Enables software flow control with configured parameters.
293    Enabled {
294        /// Xon flow control byte.
295        xon_char: u8,
296        /// Xoff flow control byte.
297        xoff_char: u8,
298        /// If the software flow control is enabled and the data amount in
299        /// rxfifo is less than xon_thrd, an xon_char will be sent.
300        xon_threshold: u8,
301        /// If the software flow control is enabled and the data amount in
302        /// rxfifo is more than xoff_thrd, an xoff_char will be sent
303        xoff_threshold: u8,
304    },
305}
306
307/// Configuration for CTS (Clear To Send) flow control.
308#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
309#[cfg_attr(feature = "defmt", derive(defmt::Format))]
310#[instability::unstable]
311pub enum CtsConfig {
312    /// Enables CTS flow control (TX).
313    Enabled,
314    #[default]
315    /// Disables CTS flow control (TX).
316    Disabled,
317}
318
319/// Configuration for RTS (Request To Send) flow control.
320#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
321#[cfg_attr(feature = "defmt", derive(defmt::Format))]
322#[instability::unstable]
323pub enum RtsConfig {
324    /// Enables RTS flow control with a FIFO threshold (RX).
325    Enabled(u8),
326    #[default]
327    /// Disables RTS flow control.
328    Disabled,
329}
330
331/// Hardware flow control configuration.
332#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
333#[cfg_attr(feature = "defmt", derive(defmt::Format))]
334#[instability::unstable]
335pub struct HwFlowControl {
336    /// CTS configuration.
337    pub cts: CtsConfig,
338    /// RTS configuration.
339    pub rts: RtsConfig,
340}
341
342/// Defines how strictly the requested baud rate must be met.
343#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
344#[cfg_attr(feature = "defmt", derive(defmt::Format))]
345#[instability::unstable]
346pub enum BaudrateTolerance {
347    /// Accepts the closest achievable baud rate without restriction.
348    #[default]
349    Closest,
350    /// In this setting, the deviation of only 1% from the desired baud value is
351    /// tolerated.
352    Exact,
353    /// Allows a certain percentage of deviation.
354    ErrorPercent(u8),
355}
356
357/// UART Configuration
358#[derive(Debug, Clone, Copy, procmacros::BuilderLite)]
359#[cfg_attr(feature = "defmt", derive(defmt::Format))]
360#[non_exhaustive]
361pub struct Config {
362    /// The baud rate (speed) of the UART communication in bits per second
363    /// (bps).
364    baudrate: u32,
365    /// Determines how close to the desired baud rate value the driver should
366    /// set the baud rate.
367    #[builder_lite(unstable)]
368    baudrate_tolerance: BaudrateTolerance,
369    /// Number of data bits in each frame (5, 6, 7, or 8 bits).
370    data_bits: DataBits,
371    /// Parity setting (None, Even, or Odd).
372    parity: Parity,
373    /// Number of stop bits in each frame (1, 1.5, or 2 bits).
374    stop_bits: StopBits,
375    /// Software flow control.
376    #[builder_lite(unstable)]
377    sw_flow_ctrl: SwFlowControl,
378    /// Hardware flow control.
379    #[builder_lite(unstable)]
380    hw_flow_ctrl: HwFlowControl,
381    /// Clock source used by the UART peripheral.
382    #[builder_lite(unstable)]
383    clock_source: ClockSource,
384    /// UART Receive part configuration.
385    rx: RxConfig,
386    /// UART Transmit part configuration.
387    tx: TxConfig,
388}
389
390impl Default for Config {
391    fn default() -> Config {
392        Config {
393            rx: RxConfig::default(),
394            tx: TxConfig::default(),
395            baudrate: 115_200,
396            baudrate_tolerance: BaudrateTolerance::default(),
397            data_bits: Default::default(),
398            parity: Default::default(),
399            stop_bits: Default::default(),
400            sw_flow_ctrl: Default::default(),
401            hw_flow_ctrl: Default::default(),
402            clock_source: Default::default(),
403        }
404    }
405}
406
407impl Config {
408    fn validate(&self) -> Result<(), ConfigError> {
409        if let BaudrateTolerance::ErrorPercent(percentage) = self.baudrate_tolerance {
410            assert!(percentage > 0 && percentage <= 100);
411        }
412
413        // Max supported baud rate is 5Mbaud
414        if self.baudrate == 0 || self.baudrate > 5_000_000 {
415            return Err(ConfigError::BaudrateNotSupported);
416        }
417        Ok(())
418    }
419}
420
421/// UART Receive part configuration.
422#[derive(Debug, Clone, Copy, procmacros::BuilderLite)]
423#[cfg_attr(feature = "defmt", derive(defmt::Format))]
424#[non_exhaustive]
425pub struct RxConfig {
426    /// Threshold level at which the RX FIFO is considered full.
427    fifo_full_threshold: u16,
428    /// Optional timeout value for RX operations.
429    timeout: Option<u8>,
430    /// RX error conditions that read operations should report.
431    ///
432    /// Error conditions not present in this set are cleared and ignored by
433    /// UART read operations.
434    #[builder_lite(unstable, into)]
435    reported_errors: EnumSet<RxErrorKind>,
436    /// Whether received bytes with UART errors are discarded by the hardware.
437    ///
438    /// When set to `true` (the default), bytes with UART errors (for example
439    /// parity or framing errors) are not stored in the RX FIFO. Set this to
440    /// `false` to keep those bytes in the RX FIFO. Use
441    /// [`Self::with_reported_errors`] to control whether those error
442    /// conditions make read operations fail.
443    #[builder_lite(unstable)]
444    discard_erroneous_bytes: bool,
445}
446
447impl Default for RxConfig {
448    fn default() -> RxConfig {
449        RxConfig {
450            // see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L61>
451            fifo_full_threshold: 120,
452            // see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L63>
453            timeout: Some(10),
454            reported_errors: EnumSet::all(),
455            discard_erroneous_bytes: true,
456        }
457    }
458}
459
460/// UART Transmit part configuration.
461#[derive(Debug, Clone, Copy, procmacros::BuilderLite)]
462#[cfg_attr(feature = "defmt", derive(defmt::Format))]
463#[non_exhaustive]
464pub struct TxConfig {
465    /// Threshold level at which the TX FIFO is considered empty.
466    fifo_empty_threshold: u16,
467}
468
469impl Default for TxConfig {
470    fn default() -> TxConfig {
471        TxConfig {
472            // see <https://github.com/espressif/esp-idf/blob/8760e6d2a/components/esp_driver_uart/src/uart.c#L59>
473            fifo_empty_threshold: 10,
474        }
475    }
476}
477
478/// Configuration for the AT-CMD detection functionality
479#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, procmacros::BuilderLite)]
480#[cfg_attr(feature = "defmt", derive(defmt::Format))]
481#[instability::unstable]
482#[non_exhaustive]
483pub struct AtCmdConfig {
484    /// Optional idle time before the AT command detection begins, in clock
485    /// cycles.
486    pre_idle_count: Option<u16>,
487    /// Optional idle time after the AT command detection ends, in clock
488    /// cycles.
489    post_idle_count: Option<u16>,
490    /// Optional timeout between bytes in the AT command, in clock
491    /// cycles.
492    gap_timeout: Option<u16>,
493    /// The byte (character) that triggers the AT command detection.
494    cmd_char: u8,
495    /// Optional number of bytes to detect as part of the AT command.
496    char_num: u8,
497}
498
499impl Default for AtCmdConfig {
500    fn default() -> Self {
501        Self {
502            pre_idle_count: None,
503            post_idle_count: None,
504            gap_timeout: None,
505            cmd_char: b'+',
506            char_num: 1,
507        }
508    }
509}
510
511/// The number of edges that the hardware counts before the threshold register starts.
512#[cfg(sleep_driver_supported)]
513const WAKEUP_EDGE_OFFSET: u16 = cfg_select! {
514    esp32 => 2,
515    esp32p4 => 6,
516    _ => 3,
517};
518
519/// The smallest number of rising edges that the hardware can wake on.
520#[cfg(sleep_driver_supported)]
521const MIN_WAKEUP_EDGES: u16 = cfg_select! {
522    // With a threshold of zero, esp32 wakes again and again.
523    esp32 => WAKEUP_EDGE_OFFSET + 1,
524    _ => WAKEUP_EDGE_OFFSET,
525};
526
527/// The largest number of rising edges that the hardware can count in its 10-bit field.
528#[cfg(sleep_driver_supported)]
529const MAX_WAKEUP_EDGES: u16 = WAKEUP_EDGE_OFFSET + 0x3FF;
530
531/// Configures how the UART wakes the chip from light sleep.
532///
533/// See [`UartRx::enable_wakeup`].
534#[cfg(sleep_driver_supported)]
535#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, procmacros::BuilderLite)]
536#[cfg_attr(feature = "defmt", derive(defmt::Format))]
537#[instability::unstable]
538#[non_exhaustive]
539pub struct WakeupConfig {
540    /// The number of rising edges on the RX line that wakes the chip.
541    ///
542    /// The hardware counts edges, and not bytes, so the number of bytes that the chip needs
543    /// depends on the data of the sender. Each byte gives one rising edge at its stop bit, and
544    /// one more edge for each change from 0 to 1 in the data. The number of edges is therefore
545    /// the smallest possible number of bytes. The default is the smallest value that the
546    /// hardware accepts.
547    ///
548    /// The permitted range on this chip is
549    #[cfg_attr(esp32, doc = "`3..=1025`.")]
550    #[cfg_attr(esp32p4, doc = "`6..=1029`.")]
551    #[cfg_attr(not(any(esp32, esp32p4)), doc = "`3..=1026`.")]
552    rising_edges: u16,
553}
554
555#[cfg(sleep_driver_supported)]
556impl Default for WakeupConfig {
557    fn default() -> Self {
558        Self {
559            rising_edges: MIN_WAKEUP_EDGES,
560        }
561    }
562}
563
564/// A wakeup configuration error.
565#[cfg(sleep_driver_supported)]
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567#[cfg_attr(feature = "defmt", derive(defmt::Format))]
568#[instability::unstable]
569#[non_exhaustive]
570pub enum WakeConfigError {
571    /// This UART instance cannot wake the chip.
572    NotAWakeupSource,
573
574    /// The hardware cannot count the requested number of rising edges.
575    EdgeCountUnsupported,
576}
577
578#[cfg(sleep_driver_supported)]
579#[instability::unstable]
580impl core::error::Error for WakeConfigError {}
581
582#[cfg(sleep_driver_supported)]
583#[instability::unstable]
584impl core::fmt::Display for WakeConfigError {
585    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
586        match self {
587            WakeConfigError::NotAWakeupSource => {
588                write!(f, "This UART instance cannot wake the chip")
589            }
590            WakeConfigError::EdgeCountUnsupported => {
591                write!(
592                    f,
593                    "The requested number of rising edges is not supported, it must be {MIN_WAKEUP_EDGES}..={MAX_WAKEUP_EDGES}"
594                )
595            }
596        }
597    }
598}
599
600struct UartBuilder<'d, Dm: DriverMode> {
601    uart: AnyUart<'d>,
602    phantom: PhantomData<Dm>,
603}
604
605impl<'d, Dm> UartBuilder<'d, Dm>
606where
607    Dm: DriverMode,
608{
609    fn new(uart: impl Instance + 'd) -> Self {
610        let uart = uart.degrade();
611
612        // Make sure inputs are well-defined.
613        // Connect RX to an idle high level.
614        uart.info().rx_signal.connect_to(&crate::gpio::Level::High);
615        uart.info().cts_signal.connect_to(&crate::gpio::Level::Low);
616
617        // Outputs only appear on the pins passed to the driver.
618        crate::gpio::disconnect_io_mux_output(uart.info().tx_signal);
619        crate::gpio::disconnect_io_mux_output(uart.info().rts_signal);
620
621        Self {
622            uart,
623            phantom: PhantomData,
624        }
625    }
626
627    fn init(self, config: Config) -> Result<Uart<'d, Dm>, ConfigError> {
628        let peri_clock_guard = UartClockGuard::new(unsafe { self.uart.clone_unchecked() });
629
630        let rts_pin = PinGuard::new_unconnected();
631        let tx_pin = PinGuard::new_unconnected();
632
633        let mut serial = Uart {
634            rx: UartRx {
635                uart: unsafe { self.uart.clone_unchecked() },
636                phantom: PhantomData,
637                peri_clock_guard: peri_clock_guard.clone(),
638                // Receiving data continuously, the peripheral can't let the system sleep.
639                _wake_lock: WakeLock::new(),
640                reported_errors: config.rx.reported_errors,
641            },
642            tx: UartTx {
643                uart: self.uart,
644                phantom: PhantomData,
645                peri_clock_guard,
646                rts_pin,
647                tx_pin,
648                baudrate: config.baudrate,
649            },
650        };
651        serial.init(config)?;
652
653        Ok(serial)
654    }
655}
656
657#[procmacros::doc_replace]
658/// UART (Full-duplex)
659///
660/// # Examples
661///
662/// ```rust, no_run
663/// # {before_snippet}
664/// use esp_hal::uart::{Config, Uart};
665/// let mut uart = Uart::new(peripherals.UART0, Config::default())?
666///     .with_rx(peripherals.GPIO1)
667///     .with_tx(peripherals.GPIO2);
668///
669/// uart.write(b"Hello world!")?;
670/// # {after_snippet}
671/// ```
672pub struct Uart<'d, Dm: DriverMode> {
673    rx: UartRx<'d, Dm>,
674    tx: UartTx<'d, Dm>,
675}
676
677/// UART (Transmit)
678#[instability::unstable]
679pub struct UartTx<'d, Dm: DriverMode> {
680    uart: AnyUart<'d>,
681    phantom: PhantomData<Dm>,
682    peri_clock_guard: UartClockGuard<'d>,
683    rts_pin: PinGuard,
684    tx_pin: PinGuard,
685    baudrate: u32,
686}
687
688/// UART (Receive)
689#[instability::unstable]
690pub struct UartRx<'d, Dm: DriverMode> {
691    uart: AnyUart<'d>,
692    phantom: PhantomData<Dm>,
693    peri_clock_guard: UartClockGuard<'d>,
694    // Receiving data continuously, the peripheral can't let the system sleep.
695    _wake_lock: WakeLock,
696    reported_errors: EnumSet<RxErrorKind>,
697}
698
699/// A configuration error.
700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
701#[cfg_attr(feature = "defmt", derive(defmt::Format))]
702#[non_exhaustive]
703pub enum ConfigError {
704    /// The requested baud rate is not achievable.
705    #[cfg(feature = "unstable")]
706    #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))]
707    BaudrateNotAchievable,
708
709    /// The requested baud rate is not supported.
710    ///
711    /// Returned when:
712    ///  * the baud rate exceeds 5MBaud or is equal to zero.
713    ///  * an exact baud rate or a deviation tolerance is specified, and the driver cannot reach
714    ///    that speed.
715    BaudrateNotSupported,
716
717    /// The requested timeout exceeds the maximum value (.
718    #[cfg_attr(esp32, doc = "127")]
719    #[cfg_attr(not(esp32), doc = "1023")]
720    /// ).
721    TimeoutTooLong,
722
723    /// The requested RX FIFO threshold exceeds the maximum value (127 bytes).
724    RxFifoThresholdNotSupported,
725
726    /// The requested TX FIFO threshold exceeds the maximum value (127 bytes).
727    TxFifoThresholdNotSupported,
728}
729
730impl core::error::Error for ConfigError {}
731
732impl core::fmt::Display for ConfigError {
733    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
734        match self {
735            #[cfg(feature = "unstable")]
736            ConfigError::BaudrateNotAchievable => {
737                write!(f, "The requested baud rate is not achievable")
738            }
739            ConfigError::BaudrateNotSupported => {
740                write!(f, "The requested baud rate is not supported")
741            }
742            ConfigError::TimeoutTooLong => write!(f, "The requested timeout is not supported"),
743            ConfigError::RxFifoThresholdNotSupported => {
744                write!(f, "The requested RX FIFO threshold is not supported")
745            }
746            ConfigError::TxFifoThresholdNotSupported => {
747                write!(f, "The requested TX FIFO threshold is not supported")
748            }
749        }
750    }
751}
752
753impl<'d> UartTx<'d, Blocking> {
754    #[procmacros::doc_replace]
755    /// Creates a new UART TX instance in [`Blocking`] mode.
756    ///
757    /// # Examples
758    ///
759    /// ```rust, no_run
760    /// # {before_snippet}
761    /// use esp_hal::uart::{Config, UartTx};
762    /// let tx = UartTx::new(peripherals.UART0, Config::default())?.with_tx(peripherals.GPIO1);
763    /// # {after_snippet}
764    /// ```
765    ///
766    /// # Errors
767    ///
768    /// [`ConfigError`] when the configuration is not supported by the hardware
769    #[instability::unstable]
770    pub fn new(uart: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
771        let (_, uart_tx) = UartBuilder::new(uart).init(config)?.split();
772
773        Ok(uart_tx)
774    }
775
776    /// Reconfigures the driver to operate in [`Async`] mode.
777    #[instability::unstable]
778    pub fn into_async(self) -> UartTx<'d, Async> {
779        if !self.uart.state().is_rx_async.load(Ordering::Acquire) {
780            self.uart
781                .set_interrupt_handler(self.uart.info().async_handler);
782        }
783        self.uart.state().is_tx_async.store(true, Ordering::Release);
784
785        UartTx {
786            uart: self.uart,
787            phantom: PhantomData,
788            peri_clock_guard: self.peri_clock_guard,
789            rts_pin: self.rts_pin,
790            tx_pin: self.tx_pin,
791            baudrate: self.baudrate,
792        }
793    }
794}
795
796impl<'d> UartTx<'d, Async> {
797    /// Reconfigures the driver to operate in [`Blocking`] mode.
798    #[instability::unstable]
799    pub fn into_blocking(self) -> UartTx<'d, Blocking> {
800        self.uart
801            .state()
802            .is_tx_async
803            .store(false, Ordering::Release);
804        if !self.uart.state().is_rx_async.load(Ordering::Acquire) {
805            self.uart.disable_peri_interrupt_on_all_cores();
806        }
807
808        UartTx {
809            uart: self.uart,
810            phantom: PhantomData,
811            peri_clock_guard: self.peri_clock_guard,
812            rts_pin: self.rts_pin,
813            tx_pin: self.tx_pin,
814            baudrate: self.baudrate,
815        }
816    }
817
818    /// Writes data into the TX buffer.
819    ///
820    /// Writes the provided buffer `bytes` into the UART transmit buffer. If the
821    /// buffer is full, waits asynchronously for space in the buffer to become
822    /// available.
823    ///
824    /// Returns the number of bytes written into the buffer. This may be less
825    /// than the length of the buffer.
826    ///
827    /// Upon an error, returns immediately and the contents of the internal FIFO
828    /// are not modified.
829    ///
830    /// # Cancellation Safety
831    ///
832    /// Cancellation safe.
833    pub async fn write_async(&mut self, bytes: &[u8]) -> Result<usize, TxError> {
834        // We need to loop in case the TX empty interrupt was fired but not cleared
835        // before, but the FIFO itself was filled up by a previous write.
836        let space = loop {
837            let tx_fifo_count = self.uart.info().tx_fifo_count();
838            let space = Info::UART_FIFO_SIZE - tx_fifo_count;
839            if space != 0 {
840                break space;
841            }
842            UartTxFuture::new(self.uart.reborrow(), TxEvent::FiFoEmpty).await;
843        };
844
845        let free = (space as usize).min(bytes.len());
846
847        for &byte in &bytes[..free] {
848            self.uart
849                .info()
850                .regs()
851                .fifo()
852                .write(|w| unsafe { w.rxfifo_rd_byte().bits(byte) });
853        }
854
855        Ok(free)
856    }
857
858    /// Asynchronously flushes the UART transmit buffer.
859    ///
860    /// Ensures that all pending data in the transmit FIFO has been sent over the
861    /// UART. If the FIFO contains data, waits for the transmission to complete
862    /// before returning.
863    ///
864    /// # Cancellation Safety
865    ///
866    /// Cancellation safe.
867    pub async fn flush_async(&mut self) -> Result<(), TxError> {
868        // Nothing is guaranteed to clear the Done status, so let's loop here in case Tx
869        // was Done before the last write operation that pushed data into the
870        // FIFO.
871        while self.uart.info().tx_fifo_count() > 0 {
872            UartTxFuture::new(self.uart.reborrow(), TxEvent::Done).await;
873        }
874
875        self.flush_last_byte();
876
877        Ok(())
878    }
879
880    /// Sends a break signal for a specified duration in bit time.
881    ///
882    /// Duration is in bits, the time it takes to transfer one bit at the
883    /// current baud rate.
884    ///
885    /// Restores the original TX line state after the break signal is sent, even if
886    /// the future is cancelled.
887    #[instability::unstable]
888    pub async fn send_break_async<D: DelayNs>(&mut self, delay: &mut D, bits: u32) {
889        // Calculate total delay in microseconds
890        let total_delay_us = (bits as u64 * 1_000_000) / self.baudrate as u64;
891        let delay_us = (total_delay_us as u32).max(1);
892
893        let break_guard = self.start_break();
894
895        delay.delay_us(delay_us).await;
896
897        core::mem::drop(break_guard);
898    }
899}
900
901impl<'d, Dm> UartTx<'d, Dm>
902where
903    Dm: DriverMode,
904{
905    /// Configures RTS pin.
906    #[instability::unstable]
907    pub fn with_rts(mut self, rts: impl PeripheralOutput<'d>) -> Self {
908        let rts = rts.into();
909
910        rts.apply_output_config(&OutputConfig::default());
911        rts.set_output_enable(true);
912
913        self.rts_pin = rts.connect_with_guard(self.uart.info().rts_signal);
914
915        self
916    }
917
918    /// Assigns the TX pin for UART instance.
919    ///
920    /// Sets the specified pin to push-pull output and connects it to the UART
921    /// TX signal.
922    ///
923    /// Disconnects the previous pin that was assigned with `with_tx`.
924    #[instability::unstable]
925    pub fn with_tx(mut self, tx: impl PeripheralOutput<'d>) -> Self {
926        let tx = tx.into();
927
928        // Make sure we don't cause an unexpected low pulse on the pin.
929        tx.set_output_high(true);
930        tx.apply_output_config(&OutputConfig::default());
931        tx.set_output_enable(true);
932
933        self.tx_pin = tx.connect_with_guard(self.uart.info().tx_signal);
934
935        self
936    }
937
938    #[procmacros::doc_replace(
939        "unsent_data" => {
940            cfg(esp32) => "On `UART0`, the function discards the data that the transmitter did not send yet, and the TX line goes low for a short time. A receiver reports that pulse as an error. On `UART1` and `UART2`, the function does not change the data that the transmitter did not send yet.",
941            _ => "The function discards the data that the transmitter did not send yet, and the TX line goes low for a short time. A receiver reports that pulse as an error."
942        }
943    )]
944    /// Changes the configuration.
945    ///
946    /// Do not call this function while a transmission is in progress.
947    /// __unsent_data__
948    /// Call [`Self::flush`] first, to let the transmitter send the remaining data.
949    ///
950    /// # Errors
951    ///
952    /// [`ConfigError`] when the configuration is not supported by the hardware
953    #[instability::unstable]
954    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
955        self.uart
956            .info()
957            .set_tx_fifo_empty_threshold(config.tx.fifo_empty_threshold)?;
958        self.uart.info().txfifo_reset();
959        Ok(())
960    }
961
962    /// Returns whether the UART buffer is ready to accept more data.
963    ///
964    /// If this function returns `true`, [`Self::write`] will not block.
965    #[instability::unstable]
966    pub fn write_ready(&self) -> bool {
967        self.uart.info().tx_fifo_count() < Info::UART_FIFO_SIZE
968    }
969
970    /// Writes bytes.
971    ///
972    /// Writes data to the internal TX FIFO of the UART peripheral. The data is
973    /// then transmitted over the UART TX line.
974    ///
975    /// Returns the number of bytes written to the FIFO. This may be less than the
976    /// length of the provided data. Returns 0 only if the provided data is empty.
977    ///
978    /// # Errors
979    ///
980    /// [`TxError`] when an error occurred during the write operation
981    #[instability::unstable]
982    pub fn write(&mut self, data: &[u8]) -> Result<usize, TxError> {
983        self.uart.info().write(data)
984    }
985
986    fn write_all(&mut self, mut data: &[u8]) -> Result<(), TxError> {
987        while !data.is_empty() {
988            let bytes_written = self.write(data)?;
989            data = &data[bytes_written..];
990        }
991        Ok(())
992    }
993
994    /// Flushes the transmit buffer.
995    ///
996    /// Blocks until all data in the TX FIFO has been transmitted.
997    #[instability::unstable]
998    pub fn flush(&mut self) -> Result<(), TxError> {
999        while self.uart.info().tx_fifo_count() > 0 {}
1000        self.flush_last_byte();
1001        Ok(())
1002    }
1003
1004    fn flush_last_byte(&mut self) {
1005        // This function handles an edge case that happens when the TX FIFO count
1006        // changes to 0. The FSM is in the Idle state for a short while after
1007        // the last byte is moved out of the FIFO. It is unclear how long this
1008        // takes, but 10us seems to be a good enough duration to wait, for both
1009        // fast and slow baud rates.
1010        crate::rom::ets_delay_us(10);
1011        while !self.is_tx_idle() {}
1012    }
1013
1014    /// Sends a break signal for a specified duration in bit time.
1015    ///
1016    /// Duration is in bits, the time it takes to transfer one bit at the
1017    /// current baud rate. The delay during the break is just busy-waiting.
1018    #[instability::unstable]
1019    pub fn send_break(&mut self, bits: u32) {
1020        // Calculate total delay in microseconds
1021        let total_delay_us = (bits as u64 * 1_000_000) / self.baudrate as u64;
1022        let delay_us = (total_delay_us as u32).max(1);
1023
1024        let break_guard = self.start_break();
1025
1026        crate::rom::ets_delay_us(delay_us);
1027
1028        core::mem::drop(break_guard);
1029    }
1030
1031    fn start_break(&mut self) -> impl Drop + '_ {
1032        // Read the current TX inversion state
1033        let original_conf0 = self.uart.info().regs().conf0().read();
1034        let original_txd_inv = original_conf0.txd_inv().bit();
1035
1036        // Invert the TX line (toggle the current state)
1037        self.uart
1038            .info()
1039            .regs()
1040            .conf0()
1041            .modify(|_, w| w.txd_inv().bit(!original_txd_inv));
1042
1043        sync_regs(self.uart.info().regs());
1044
1045        // Restore the original register state when dropped.
1046        DropGuard::new(self, move |this| {
1047            this.uart
1048                .info()
1049                .regs()
1050                .conf0()
1051                .write(|w| unsafe { w.bits(original_conf0.bits()) });
1052            sync_regs(this.uart.info().regs());
1053        })
1054    }
1055
1056    /// Returns whether the TX line is idle for this UART instance.
1057    ///
1058    /// The transmit line is idle when no data is currently being transmitted.
1059    fn is_tx_idle(&self) -> bool {
1060        self.uart.info().is_tx_idle()
1061    }
1062
1063    /// Disables all TX-related interrupts for this UART instance.
1064    ///
1065    /// Clears and disables the `transmit FIFO empty` interrupt, `transmit break
1066    /// done`, `transmit break idle done`, and `transmit done` interrupts
1067    fn disable_tx_interrupts(&self) {
1068        self.regs().int_clr().write(|w| {
1069            w.txfifo_empty().clear_bit_by_one();
1070            w.tx_brk_done().clear_bit_by_one();
1071            w.tx_brk_idle_done().clear_bit_by_one();
1072            w.tx_done().clear_bit_by_one()
1073        });
1074
1075        self.regs().int_ena().write(|w| {
1076            w.txfifo_empty().clear_bit();
1077            w.tx_brk_done().clear_bit();
1078            w.tx_brk_idle_done().clear_bit();
1079            w.tx_done().clear_bit()
1080        });
1081    }
1082
1083    fn regs(&self) -> &RegisterBlock {
1084        self.uart.info().regs()
1085    }
1086}
1087
1088impl<'d> UartRx<'d, Blocking> {
1089    #[procmacros::doc_replace]
1090    /// Creates a new UART RX instance in [`Blocking`] mode.
1091    ///
1092    /// # Examples
1093    ///
1094    /// ```rust, no_run
1095    /// # {before_snippet}
1096    /// use esp_hal::uart::{Config, UartRx};
1097    /// let rx = UartRx::new(peripherals.UART0, Config::default())?.with_rx(peripherals.GPIO2);
1098    /// # {after_snippet}
1099    /// ```
1100    ///
1101    /// # Errors
1102    ///
1103    /// [`ConfigError`] when the configuration is not supported by the hardware
1104    #[instability::unstable]
1105    pub fn new(uart: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
1106        let (uart_rx, _) = UartBuilder::new(uart).init(config)?.split();
1107
1108        Ok(uart_rx)
1109    }
1110
1111    /// Waits for a break condition to be detected.
1112    ///
1113    /// Polls the break-detection interrupt status and returns once the receiver
1114    /// has detected a break condition. After detection, the break status is
1115    /// automatically cleared.
1116    #[instability::unstable]
1117    pub fn wait_for_break(&mut self) {
1118        while !self.is_break_detected() {
1119            // wait
1120        }
1121
1122        self.clear_break_detected();
1123    }
1124
1125    /// Waits for a break condition to be detected with a timeout.
1126    ///
1127    /// Polls the break-detection interrupt status until a break is detected or
1128    /// the specified timeout expires. Returns whether a break was detected
1129    /// before the timeout expired. After successful detection, the break
1130    /// status is automatically cleared.
1131    ///
1132    /// ## Arguments
1133    /// * `timeout` - Maximum time to wait for a break condition
1134    #[instability::unstable]
1135    pub fn wait_for_break_with_timeout(&mut self, timeout: crate::time::Duration) -> bool {
1136        let start = crate::time::Instant::now();
1137
1138        while !self.is_break_detected() {
1139            if crate::time::Instant::now() - start >= timeout {
1140                return false;
1141            }
1142        }
1143
1144        self.clear_break_detected();
1145        true
1146    }
1147
1148    /// Reconfigures the driver to operate in [`Async`] mode.
1149    #[instability::unstable]
1150    pub fn into_async(self) -> UartRx<'d, Async> {
1151        if !self.uart.state().is_tx_async.load(Ordering::Acquire) {
1152            self.uart
1153                .set_interrupt_handler(self.uart.info().async_handler);
1154        }
1155        self.uart.state().is_rx_async.store(true, Ordering::Release);
1156
1157        UartRx {
1158            uart: self.uart,
1159            phantom: PhantomData,
1160            peri_clock_guard: self.peri_clock_guard,
1161            _wake_lock: self._wake_lock,
1162            reported_errors: self.reported_errors,
1163        }
1164    }
1165}
1166
1167impl<'d> UartRx<'d, Async> {
1168    /// Reconfigures the driver to operate in [`Blocking`] mode.
1169    #[instability::unstable]
1170    pub fn into_blocking(self) -> UartRx<'d, Blocking> {
1171        self.uart
1172            .state()
1173            .is_rx_async
1174            .store(false, Ordering::Release);
1175        if !self.uart.state().is_tx_async.load(Ordering::Acquire) {
1176            self.uart.disable_peri_interrupt_on_all_cores();
1177        }
1178
1179        UartRx {
1180            uart: self.uart,
1181            phantom: PhantomData,
1182            peri_clock_guard: self.peri_clock_guard,
1183            _wake_lock: self._wake_lock,
1184            reported_errors: self.reported_errors,
1185        }
1186    }
1187
1188    async fn wait_for_buffered_data(
1189        &mut self,
1190        minimum: usize,
1191        max_threshold: usize,
1192        listen_for_timeout: bool,
1193    ) -> Result<(), RxError> {
1194        let current_threshold = self.uart.info().rx_fifo_full_threshold();
1195
1196        // User preference takes priority.
1197        let max_threshold = max_threshold.min(current_threshold as usize) as u16;
1198        let minimum = minimum.min(Info::RX_FIFO_MAX_THRHD as usize) as u16;
1199
1200        // The effective threshold must be >= minimum. We ensure this by lowering the minimum number
1201        // of returnable bytes.
1202        let minimum = minimum.min(max_threshold);
1203
1204        // loop to prevent returning 0 bytes
1205        while self.uart.info().rx_fifo_count() < minimum {
1206            // We're ignoring the user configuration here to ensure that this is not waiting
1207            // for more data than the buffer. We'll restore the original value after the
1208            // future resolved.
1209            let info = self.uart.info();
1210            unwrap!(info.set_rx_fifo_full_threshold(max_threshold));
1211            let _guard = DropGuard::new((), |_| {
1212                unwrap!(info.set_rx_fifo_full_threshold(current_threshold));
1213            });
1214
1215            // Wait for space or event
1216            let mut events = RxEvent::FifoFull
1217                | RxEvent::FifoOvf
1218                | RxEvent::FrameError
1219                | RxEvent::GlitchDetected
1220                | RxEvent::ParityError;
1221
1222            if self.regs().at_cmd_char().read().char_num().bits() > 0 {
1223                events |= RxEvent::CmdCharDetected;
1224            }
1225
1226            if listen_for_timeout && self.uart.info().rx_timeout_enabled() {
1227                events |= RxEvent::FifoTout;
1228            }
1229
1230            let events = UartRxFuture::new(self.uart.reborrow(), events).await;
1231
1232            if events.contains(RxEvent::FifoOvf) {
1233                self.uart.info().rxfifo_reset();
1234            }
1235            rx_event_check_for_error(events, self.reported_errors)?;
1236        }
1237
1238        Ok(())
1239    }
1240
1241    /// Reads data asynchronously.
1242    ///
1243    /// Reads data from the UART receive buffer into the provided buffer. If the
1244    /// buffer is empty, waits asynchronously for data to become available, or for
1245    /// an error to occur.
1246    ///
1247    /// Returns the number of bytes read into the buffer. This may be less than
1248    /// the length of the buffer.
1249    ///
1250    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
1251    /// wait for more data than the buffer can hold.
1252    ///
1253    /// Upon an error, returns immediately and the contents of the internal FIFO
1254    /// are not modified.
1255    ///
1256    /// # Cancellation Safety
1257    ///
1258    /// Cancellation safe.
1259    pub async fn read_async(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
1260        if buf.is_empty() {
1261            return Ok(0);
1262        }
1263
1264        self.wait_for_buffered_data(1, buf.len(), true).await?;
1265
1266        self.read_buffered(buf)
1267    }
1268
1269    /// Fills buffer asynchronously.
1270    ///
1271    /// Reads data into the provided buffer. If the internal FIFO does not contain
1272    /// enough data, waits asynchronously for data to become available, or for an
1273    /// error to occur.
1274    ///
1275    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
1276    /// wait for more data than the buffer can hold.
1277    ///
1278    /// # Cancellation Safety
1279    ///
1280    /// **Not** cancellation safe. If the future is dropped before it resolves, or
1281    /// if an error occurs during the read operation, previously read data may be
1282    /// lost.
1283    pub async fn read_exact_async(&mut self, mut buf: &mut [u8]) -> Result<(), RxError> {
1284        if buf.is_empty() {
1285            return Ok(());
1286        }
1287
1288        // Drain the buffer first, there's no point in waiting for data we've already received.
1289        let read = self.read_buffered(buf)?;
1290        buf = &mut buf[read..];
1291
1292        while !buf.is_empty() {
1293            // No point in listening for timeouts, as we're waiting for an exact amount of
1294            // data. On ESP32 and S2, the timeout interrupt can't be cleared unless the FIFO
1295            // is empty, so listening could cause an infinite loop here.
1296            self.wait_for_buffered_data(buf.len(), buf.len(), false)
1297                .await?;
1298
1299            let read = self.read_buffered(buf)?;
1300            buf = &mut buf[read..];
1301        }
1302
1303        Ok(())
1304    }
1305
1306    /// Waits for a break condition to be detected asynchronously.
1307    ///
1308    /// This is an async function that will await until a break condition is
1309    /// detected on the RX line. After detection, the break interrupt flag is
1310    /// automatically cleared.
1311    #[instability::unstable]
1312    pub async fn wait_for_break_async(&mut self) {
1313        UartRxFuture::new(self.uart.reborrow(), RxEvent::BreakDetected).await;
1314    }
1315}
1316
1317impl<'d, Dm> UartRx<'d, Dm>
1318where
1319    Dm: DriverMode,
1320{
1321    fn regs(&self) -> &RegisterBlock {
1322        self.uart.info().regs()
1323    }
1324
1325    /// Assigns the CTS pin for UART instance.
1326    ///
1327    /// Sets the specified pin to input and connects it to the UART CTS signal.
1328    #[instability::unstable]
1329    pub fn with_cts(self, cts: impl PeripheralInput<'d>) -> Self {
1330        let cts = cts.into();
1331
1332        cts.apply_input_config(&InputConfig::default());
1333        cts.set_input_enable(true);
1334
1335        self.uart.info().cts_signal.connect_to(&cts);
1336
1337        self
1338    }
1339
1340    /// Assigns the RX pin for UART instance.
1341    ///
1342    /// Sets the specified pin to input and connects it to the UART RX signal.
1343    ///
1344    /// When listening for the output of the UART peripheral, configure the driver
1345    /// side (the TX pin), or ensure that the line is initially high, to avoid
1346    /// receiving a non-data byte caused by an initial low signal level.
1347    #[instability::unstable]
1348    pub fn with_rx(self, rx: impl PeripheralInput<'d>) -> Self {
1349        let rx = rx.into();
1350
1351        rx.apply_input_config(&InputConfig::default().with_pull(Pull::Up));
1352        rx.set_input_enable(true);
1353
1354        self.uart.info().rx_signal.connect_to(&rx);
1355
1356        self
1357    }
1358
1359    /// Returns whether a break condition has been detected.
1360    ///
1361    /// The returned status is sticky and remains set until
1362    /// [`Self::clear_break_detected`] is called, or until one of the
1363    /// `wait_for_break` methods observes and clears it.
1364    #[instability::unstable]
1365    pub fn is_break_detected(&self) -> bool {
1366        self.uart.info().check_rx_break_detected()
1367    }
1368
1369    /// Clears the break-detection status.
1370    #[instability::unstable]
1371    pub fn clear_break_detected(&mut self) {
1372        self.uart.info().clear_rx_break_detected();
1373    }
1374
1375    /// Changes the configuration.
1376    ///
1377    /// # Errors
1378    ///
1379    /// [`ConfigError`] when the configuration is not supported by the hardware
1380    #[instability::unstable]
1381    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
1382        self.uart
1383            .info()
1384            .set_rx_fifo_full_threshold(config.rx.fifo_full_threshold)?;
1385        self.uart
1386            .info()
1387            .set_rx_timeout(config.rx.timeout, self.uart.info().current_symbol_length())?;
1388        self.uart
1389            .info()
1390            .set_discard_erroneous_bytes(config.rx.discard_erroneous_bytes);
1391        self.reported_errors = config.rx.reported_errors;
1392
1393        self.uart.info().rxfifo_reset();
1394        Ok(())
1395    }
1396
1397    /// Lets activity on the RX line wake the chip from light sleep.
1398    ///
1399    /// The chip wakes when it counts the number of rising edges that
1400    /// [`WakeupConfig::with_rising_edges`] gives. Deep sleep powers the UART down, so this source
1401    /// ends a light sleep only.
1402    ///
1403    /// The chip loses the bytes that cause the wake. It also loses the bytes that arrive during the
1404    /// wake, and at a typical baud rate that wake is long enough to lose several bytes. A sender
1405    /// must therefore first send data that the receiver can lose, and then send the data again.
1406    /// The first data after the wake also clears the internal wakeup indication. Without that
1407    /// write, the next wake occurs two edges early.
1408    ///
1409    /// The peripheral counts the edges itself, so a light sleep keeps the high-performance
1410    /// peripherals powered instead of powering them down. This increases the sleep current.
1411    ///
1412    /// The configuration stays after the driver is dropped, so that the UART continues to wake the
1413    /// chip while no driver owns it. Call [`Self::disable_wakeup`] to remove it.
1414    ///
1415    /// # Errors
1416    ///
1417    /// [`WakeConfigError::NotAWakeupSource`] when this UART instance cannot wake the chip,
1418    /// and [`WakeConfigError::EdgeCountUnsupported`] when the hardware cannot count the requested
1419    /// number of edges.
1420    #[cfg(sleep_driver_supported)]
1421    #[instability::unstable]
1422    pub fn enable_wakeup(&mut self, config: &WakeupConfig) -> Result<(), WakeConfigError> {
1423        self.uart.info().enable_wakeup(config)
1424    }
1425
1426    /// Stops the UART from waking the chip.
1427    #[cfg(sleep_driver_supported)]
1428    #[instability::unstable]
1429    pub fn disable_wakeup(&mut self) {
1430        self.uart.info().disable_wakeup();
1431    }
1432
1433    /// Reads and clears RX error conditions set by received data.
1434    ///
1435    /// Only errors enabled in [`RxConfig::with_reported_errors`] are returned;
1436    /// disabled errors are cleared and ignored.
1437    ///
1438    /// If a FIFO overflow is detected, the RX FIFO is reset.
1439    #[instability::unstable]
1440    pub fn check_for_errors(&mut self) -> Result<(), RxError> {
1441        self.uart.info().check_for_errors(self.reported_errors)
1442    }
1443
1444    /// Returns whether the UART buffer has data.
1445    ///
1446    /// If this function returns `true`, [`Self::read`] will not block.
1447    #[instability::unstable]
1448    pub fn read_ready(&self) -> bool {
1449        self.uart.info().rx_fifo_count() > 0
1450    }
1451
1452    /// Reads bytes.
1453    ///
1454    /// The UART hardware continuously receives bytes and stores them in the RX
1455    /// FIFO. Reads the bytes from the RX FIFO and returns them in the provided
1456    /// buffer. If the hardware buffer is empty, blocks until data is available.
1457    /// [`Self::read_ready`] can be used to check if data is available without
1458    /// blocking.
1459    ///
1460    /// Returns the number of bytes read into the buffer. This may be less than
1461    /// the length of the buffer. Returns 0 only if the provided buffer is empty.
1462    ///
1463    /// # Errors
1464    ///
1465    /// [`RxError`] when a reported error occurred since
1466    /// the last call to [`Self::check_for_errors`], [`Self::read_buffered`], or
1467    /// this function.
1468    ///
1469    /// If the error occurred before this function was called, the contents of
1470    /// the FIFO are not modified.
1471    #[instability::unstable]
1472    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
1473        self.uart.info().read(buf, self.reported_errors)
1474    }
1475
1476    /// Reads already received bytes.
1477    ///
1478    /// Reads the already received bytes from the FIFO into the provided buffer.
1479    /// Does not wait for the FIFO to actually contain any bytes.
1480    ///
1481    /// Returns the number of bytes read into the buffer. This may be less than
1482    /// the length of the buffer, and it may also be 0.
1483    ///
1484    /// # Errors
1485    ///
1486    /// [`RxError`] when a reported error occurred since
1487    /// the last call to [`Self::check_for_errors`], [`Self::read`], or this
1488    /// function.
1489    ///
1490    /// If the error occurred before this function was called, the contents of
1491    /// the FIFO are not modified.
1492    #[instability::unstable]
1493    pub fn read_buffered(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
1494        self.uart.info().read_buffered(buf, self.reported_errors)
1495    }
1496
1497    /// Disables all RX-related interrupts for this UART instance.
1498    ///
1499    /// Clears and disables the `receive FIFO full` interrupt, `receive FIFO
1500    /// overflow`, `receive FIFO timeout`, and `AT command byte detection`
1501    /// interrupts.
1502    fn disable_rx_interrupts(&self) {
1503        self.regs().int_clr().write(|w| {
1504            w.rxfifo_full().clear_bit_by_one();
1505            w.rxfifo_ovf().clear_bit_by_one();
1506            w.rxfifo_tout().clear_bit_by_one();
1507            w.at_cmd_char_det().clear_bit_by_one()
1508        });
1509
1510        self.regs().int_ena().write(|w| {
1511            w.rxfifo_full().clear_bit();
1512            w.rxfifo_ovf().clear_bit();
1513            w.rxfifo_tout().clear_bit();
1514            w.at_cmd_char_det().clear_bit()
1515        });
1516    }
1517}
1518
1519impl<'d> Uart<'d, Blocking> {
1520    #[procmacros::doc_replace]
1521    /// Creates a new UART instance in [`Blocking`] mode.
1522    ///
1523    /// # Examples
1524    ///
1525    /// ```rust, no_run
1526    /// # {before_snippet}
1527    /// use esp_hal::uart::{Config, Uart};
1528    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
1529    ///     .with_rx(peripherals.GPIO1)
1530    ///     .with_tx(peripherals.GPIO2);
1531    /// # {after_snippet}
1532    /// ```
1533    ///
1534    /// # Errors
1535    ///
1536    /// [`ConfigError`] when the configuration is not supported by the hardware
1537    pub fn new(uart: impl Instance + 'd, config: Config) -> Result<Self, ConfigError> {
1538        UartBuilder::new(uart).init(config)
1539    }
1540
1541    /// Reconfigures the driver to operate in [`Async`] mode.
1542    ///
1543    /// See the [`Async`] documentation for an example on how to use this
1544    /// method.
1545    pub fn into_async(self) -> Uart<'d, Async> {
1546        Uart {
1547            rx: self.rx.into_async(),
1548            tx: self.tx.into_async(),
1549        }
1550    }
1551
1552    #[cfg_attr(
1553        not(multi_core),
1554        doc = "Registers an interrupt handler for the peripheral."
1555    )]
1556    #[cfg_attr(
1557        multi_core,
1558        doc = "Registers an interrupt handler for the peripheral on the current core."
1559    )]
1560    #[doc = ""]
1561    /// Replaces any previously registered interrupt handlers.
1562    ///
1563    /// The default/unhandled interrupt handler can be restored with
1564    /// [crate::interrupt::DEFAULT_INTERRUPT_HANDLER]
1565    #[instability::unstable]
1566    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
1567        // `self.tx.uart` and `self.rx.uart` are the same
1568        self.tx.uart.set_interrupt_handler(handler);
1569    }
1570
1571    #[procmacros::doc_replace]
1572    /// Listens for the given interrupts.
1573    ///
1574    /// # Examples
1575    ///
1576    /// **Note**: In practice a proper serial terminal should be used
1577    /// to connect to the board (espflash will not work)
1578    ///
1579    /// ```rust, no_run
1580    /// # {before_snippet}
1581    /// use esp_hal::{
1582    ///     delay::Delay,
1583    ///     uart::{AtCmdConfig, Config, RxConfig, Uart, UartInterrupt},
1584    /// };
1585    /// # let delay = Delay::new();
1586    /// # let config = Config::default().with_rx(
1587    /// #    RxConfig::default().with_fifo_full_threshold(30)
1588    /// # );
1589    /// # let mut uart = Uart::new(
1590    /// #    peripherals.UART0,
1591    /// #    config)?;
1592    /// uart.set_interrupt_handler(interrupt_handler);
1593    ///
1594    /// critical_section::with(|cs| {
1595    ///     uart.set_at_cmd(AtCmdConfig::default().with_cmd_char(b'#'));
1596    ///     uart.listen(UartInterrupt::AtCmd | UartInterrupt::RxFifoFull);
1597    ///
1598    ///     SERIAL.borrow_ref_mut(cs).replace(uart);
1599    /// });
1600    ///
1601    /// loop {
1602    ///     println!("Send `#` character or >=30 characters");
1603    ///     delay.delay(Duration::from_secs(1));
1604    /// }
1605    /// # }
1606    ///
1607    /// use core::cell::RefCell;
1608    ///
1609    /// use critical_section::Mutex;
1610    /// use esp_hal::uart::Uart;
1611    /// static SERIAL: Mutex<RefCell<Option<Uart<esp_hal::Blocking>>>> = Mutex::new(RefCell::new(None));
1612    ///
1613    /// use core::fmt::Write;
1614    ///
1615    /// use esp_hal::uart::UartInterrupt;
1616    /// #[esp_hal::handler]
1617    /// fn interrupt_handler() {
1618    ///     critical_section::with(|cs| {
1619    ///         let mut serial = SERIAL.borrow_ref_mut(cs);
1620    ///         if let Some(serial) = serial.as_mut() {
1621    ///             let mut buf = [0u8; 64];
1622    ///             if let Ok(cnt) = serial.read_buffered(&mut buf) {
1623    ///                 println!("Read {} bytes", cnt);
1624    ///             }
1625    ///
1626    ///             let pending_interrupts = serial.interrupts();
1627    ///             println!(
1628    ///                 "Interrupt AT-CMD: {} RX-FIFO-FULL: {}",
1629    ///                 pending_interrupts.contains(UartInterrupt::AtCmd),
1630    ///                 pending_interrupts.contains(UartInterrupt::RxFifoFull),
1631    ///             );
1632    ///
1633    ///             serial.clear_interrupts(UartInterrupt::AtCmd | UartInterrupt::RxFifoFull);
1634    ///         }
1635    ///     });
1636    /// }
1637    /// ```
1638    #[instability::unstable]
1639    pub fn listen(&mut self, interrupts: impl Into<EnumSet<UartInterrupt>>) {
1640        self.tx.uart.info().enable_listen(interrupts.into(), true)
1641    }
1642
1643    /// Unlistens from the given interrupts.
1644    #[instability::unstable]
1645    pub fn unlisten(&mut self, interrupts: impl Into<EnumSet<UartInterrupt>>) {
1646        self.tx.uart.info().enable_listen(interrupts.into(), false)
1647    }
1648
1649    /// Returns the asserted interrupts.
1650    #[instability::unstable]
1651    pub fn interrupts(&mut self) -> EnumSet<UartInterrupt> {
1652        self.tx.uart.info().interrupts()
1653    }
1654
1655    /// Resets asserted interrupts.
1656    #[instability::unstable]
1657    pub fn clear_interrupts(&mut self, interrupts: EnumSet<UartInterrupt>) {
1658        self.tx.uart.info().clear_interrupts(interrupts)
1659    }
1660
1661    /// Waits for a break condition to be detected.
1662    ///
1663    /// This is a blocking function that will continuously check for a break condition.
1664    /// After detection, the break interrupt flag is automatically cleared.
1665    #[instability::unstable]
1666    pub fn wait_for_break(&mut self) {
1667        self.rx.wait_for_break()
1668    }
1669
1670    /// Waits for a break condition to be detected with a timeout.
1671    ///
1672    /// This is a blocking function that will check for a break condition up to
1673    /// the specified timeout. Returns whether a break was detected before the
1674    /// timeout expired. After successful detection, the break interrupt flag
1675    /// is automatically cleared.
1676    ///
1677    /// ## Arguments
1678    /// * `timeout` - Maximum time to wait for a break condition
1679    #[instability::unstable]
1680    pub fn wait_for_break_with_timeout(&mut self, timeout: crate::time::Duration) -> bool {
1681        self.rx.wait_for_break_with_timeout(timeout)
1682    }
1683}
1684
1685impl<'d> Uart<'d, Async> {
1686    /// Reconfigures the driver to operate in [`Blocking`] mode.
1687    ///
1688    /// See the [`Blocking`] documentation for an example on how to use this
1689    /// method.
1690    pub fn into_blocking(self) -> Uart<'d, Blocking> {
1691        Uart {
1692            rx: self.rx.into_blocking(),
1693            tx: self.tx.into_blocking(),
1694        }
1695    }
1696
1697    #[procmacros::doc_replace]
1698    /// Writes data into the TX buffer.
1699    ///
1700    /// Writes the provided buffer `bytes` into the UART transmit buffer. If the
1701    /// buffer is full, waits asynchronously for space in the buffer to become
1702    /// available.
1703    ///
1704    /// Returns the number of bytes written into the buffer. This may be less
1705    /// than the length of the buffer.
1706    ///
1707    /// Upon an error, returns immediately and the contents of the internal FIFO
1708    /// are not modified.
1709    ///
1710    /// # Examples
1711    ///
1712    /// ```rust, no_run
1713    /// # {before_snippet}
1714    /// use esp_hal::uart::{Config, Uart};
1715    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
1716    ///     .with_rx(peripherals.GPIO1)
1717    ///     .with_tx(peripherals.GPIO2)
1718    ///     .into_async();
1719    ///
1720    /// const MESSAGE: &[u8] = b"Hello, world!";
1721    /// uart.write_async(&MESSAGE).await?;
1722    /// # {after_snippet}
1723    /// ```
1724    ///
1725    /// # Cancellation Safety
1726    ///
1727    /// Cancellation safe.
1728    pub async fn write_async(&mut self, words: &[u8]) -> Result<usize, TxError> {
1729        self.tx.write_async(words).await
1730    }
1731
1732    #[procmacros::doc_replace]
1733    /// Asynchronously flushes the UART transmit buffer.
1734    ///
1735    /// Ensures that all pending data in the transmit FIFO has been sent over the
1736    /// UART. If the FIFO contains data, waits for the transmission to complete
1737    /// before returning.
1738    ///
1739    /// # Examples
1740    ///
1741    /// ```rust, no_run
1742    /// # {before_snippet}
1743    /// use esp_hal::uart::{Config, Uart};
1744    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
1745    ///     .with_rx(peripherals.GPIO1)
1746    ///     .with_tx(peripherals.GPIO2)
1747    ///     .into_async();
1748    ///
1749    /// const MESSAGE: &[u8] = b"Hello, world!";
1750    /// uart.write_async(&MESSAGE).await?;
1751    /// uart.flush_async().await?;
1752    /// # {after_snippet}
1753    /// ```
1754    ///
1755    /// # Cancellation Safety
1756    ///
1757    /// Cancellation safe.
1758    pub async fn flush_async(&mut self) -> Result<(), TxError> {
1759        self.tx.flush_async().await
1760    }
1761
1762    #[procmacros::doc_replace]
1763    /// Reads data asynchronously.
1764    ///
1765    /// Reads data from the UART receive buffer into the provided buffer. If the
1766    /// buffer is empty, waits asynchronously for data to become available, or for
1767    /// an error to occur.
1768    ///
1769    /// Returns the number of bytes read into the buffer. This may be less than
1770    /// the length of the buffer.
1771    ///
1772    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
1773    /// wait for more data than the buffer can hold.
1774    ///
1775    /// Upon an error, returns immediately and the contents of the internal FIFO
1776    /// are not modified.
1777    ///
1778    /// # Examples
1779    ///
1780    /// ```rust, no_run
1781    /// # {before_snippet}
1782    /// use esp_hal::uart::{Config, Uart};
1783    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
1784    ///     .with_rx(peripherals.GPIO1)
1785    ///     .with_tx(peripherals.GPIO2)
1786    ///     .into_async();
1787    ///
1788    /// const MESSAGE: &[u8] = b"Hello, world!";
1789    /// uart.write_async(&MESSAGE).await?;
1790    /// uart.flush_async().await?;
1791    ///
1792    /// let mut buf = [0u8; MESSAGE.len()];
1793    /// uart.read_async(&mut buf[..]).await?;
1794    /// # {after_snippet}
1795    /// ```
1796    ///
1797    /// # Cancellation Safety
1798    ///
1799    /// Cancellation safe.
1800    pub async fn read_async(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
1801        self.rx.read_async(buf).await
1802    }
1803
1804    /// Fills buffer asynchronously.
1805    ///
1806    /// Reads data from the UART receive buffer into the provided buffer. If the
1807    /// buffer is empty, waits asynchronously for data to become available, or for
1808    /// an error to occur.
1809    ///
1810    /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not
1811    /// wait for more data than the buffer can hold.
1812    ///
1813    /// # Cancellation Safety
1814    ///
1815    /// **Not** cancellation safe. If the future is dropped before it resolves, or
1816    /// if an error occurs during the read operation, previously read data may be
1817    /// lost.
1818    #[instability::unstable]
1819    pub async fn read_exact_async(&mut self, buf: &mut [u8]) -> Result<(), RxError> {
1820        self.rx.read_exact_async(buf).await
1821    }
1822
1823    /// Waits for a break condition to be detected asynchronously.
1824    ///
1825    /// This is an async function that will await until a break condition is
1826    /// detected on the RX line. After detection, the break interrupt flag is
1827    /// automatically cleared.
1828    #[instability::unstable]
1829    pub async fn wait_for_break_async(&mut self) {
1830        self.rx.wait_for_break_async().await
1831    }
1832
1833    /// Sends a break signal for a specified duration in bit time.
1834    ///
1835    /// Duration is in bits, the time it takes to transfer one bit at the
1836    /// current baud rate.
1837    ///
1838    /// Restores the original TX line state after the break signal is sent, even if
1839    /// the future is cancelled.
1840    #[instability::unstable]
1841    pub async fn send_break_async<D: DelayNs>(&mut self, delay: &mut D, bits: u32) {
1842        self.tx.send_break_async(delay, bits).await
1843    }
1844}
1845
1846/// List of exposed UART events.
1847#[derive(Debug, EnumSetType)]
1848#[cfg_attr(feature = "defmt", derive(defmt::Format))]
1849#[non_exhaustive]
1850#[instability::unstable]
1851pub enum UartInterrupt {
1852    /// Indicates that the receiver has detected the configured
1853    /// [`Uart::set_at_cmd`] byte.
1854    AtCmd,
1855
1856    /// The transmitter has finished sending out all data from the FIFO.
1857    TxDone,
1858
1859    /// Break condition has been detected.
1860    /// Triggered when the receiver detects a NULL character (i.e. logic 0 for
1861    /// one NULL character transmission) after stop bits.
1862    RxBreakDetected,
1863
1864    /// The receiver has received more data than what
1865    /// [`RxConfig::fifo_full_threshold`] specifies.
1866    RxFifoFull,
1867
1868    /// The receiver has not received any data for the time
1869    /// [`RxConfig::with_timeout`] specifies.
1870    RxTimeout,
1871}
1872
1873impl<'d, Dm> Uart<'d, Dm>
1874where
1875    Dm: DriverMode,
1876{
1877    #[procmacros::doc_replace]
1878    /// Assigns the RX pin for UART instance.
1879    ///
1880    /// Sets the specified pin to input and connects it to the UART RX signal.
1881    ///
1882    /// When listening for the output of the UART peripheral, configure the driver
1883    /// side (the TX pin), or ensure that the line is initially high, to avoid
1884    /// receiving a non-data byte caused by an initial low signal level.
1885    ///
1886    /// # Examples
1887    ///
1888    /// ```rust, no_run
1889    /// # {before_snippet}
1890    /// use esp_hal::uart::{Config, Uart};
1891    /// let uart = Uart::new(peripherals.UART0, Config::default())?.with_rx(peripherals.GPIO1);
1892    ///
1893    /// # {after_snippet}
1894    /// ```
1895    pub fn with_rx(mut self, rx: impl PeripheralInput<'d>) -> Self {
1896        self.rx = self.rx.with_rx(rx);
1897        self
1898    }
1899
1900    #[procmacros::doc_replace]
1901    /// Assigns the TX pin for UART instance.
1902    ///
1903    /// Sets the specified pin to push-pull output and connects it to the UART
1904    /// TX signal.
1905    ///
1906    /// # Examples
1907    ///
1908    /// ```rust, no_run
1909    /// # {before_snippet}
1910    /// use esp_hal::uart::{Config, Uart};
1911    /// let uart = Uart::new(peripherals.UART0, Config::default())?.with_tx(peripherals.GPIO2);
1912    ///
1913    /// # {after_snippet}
1914    /// ```
1915    pub fn with_tx(mut self, tx: impl PeripheralOutput<'d>) -> Self {
1916        self.tx = self.tx.with_tx(tx);
1917        self
1918    }
1919
1920    #[procmacros::doc_replace]
1921    /// Configures CTS pin.
1922    ///
1923    /// # Examples
1924    ///
1925    /// ```rust, no_run
1926    /// # {before_snippet}
1927    /// use esp_hal::uart::{Config, Uart};
1928    /// let uart = Uart::new(peripherals.UART0, Config::default())?
1929    ///     .with_rx(peripherals.GPIO1)
1930    ///     .with_cts(peripherals.GPIO3);
1931    ///
1932    /// # {after_snippet}
1933    /// ```
1934    pub fn with_cts(mut self, cts: impl PeripheralInput<'d>) -> Self {
1935        self.rx = self.rx.with_cts(cts);
1936        self
1937    }
1938
1939    #[procmacros::doc_replace]
1940    /// Configures RTS pin.
1941    ///
1942    /// # Examples
1943    ///
1944    /// ```rust, no_run
1945    /// # {before_snippet}
1946    /// use esp_hal::uart::{Config, Uart};
1947    /// let uart = Uart::new(peripherals.UART0, Config::default())?
1948    ///     .with_tx(peripherals.GPIO2)
1949    ///     .with_rts(peripherals.GPIO3);
1950    ///
1951    /// # {after_snippet}
1952    /// ```
1953    pub fn with_rts(mut self, rts: impl PeripheralOutput<'d>) -> Self {
1954        self.tx = self.tx.with_rts(rts);
1955        self
1956    }
1957
1958    fn regs(&self) -> &RegisterBlock {
1959        // `self.tx.uart` and `self.rx.uart` are the same
1960        self.tx.uart.info().regs()
1961    }
1962
1963    #[procmacros::doc_replace]
1964    /// Returns whether the UART TX buffer is ready to accept more data.
1965    ///
1966    /// If this function returns `true`, [`Self::write`] and [`Self::write_async`]
1967    /// will not block. Otherwise, the functions will not return until the buffer is
1968    /// ready.
1969    ///
1970    /// # Examples
1971    ///
1972    /// ```rust, no_run
1973    /// # {before_snippet}
1974    /// use esp_hal::uart::{Config, Uart};
1975    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
1976    ///
1977    /// if uart.write_ready() {
1978    ///     // Because write_ready has returned true, the following call will immediately
1979    ///     // copy some bytes into the FIFO and return a non-zero value.
1980    ///     let written = uart.write(b"Hello")?;
1981    ///     // ... handle written bytes
1982    /// } else {
1983    ///     // Calling write would have blocked, but here we can do something useful
1984    ///     // instead of waiting for the buffer to become ready.
1985    /// }
1986    /// # {after_snippet}
1987    /// ```
1988    pub fn write_ready(&self) -> bool {
1989        self.tx.write_ready()
1990    }
1991
1992    #[procmacros::doc_replace]
1993    /// Writes bytes.
1994    ///
1995    /// Writes data to the internal TX FIFO of the UART peripheral. The data is
1996    /// then transmitted over the UART TX line.
1997    ///
1998    /// Returns the number of bytes written to the FIFO. This may be less than the
1999    /// length of the provided data. Returns 0 only if the provided data is empty.
2000    ///
2001    /// # Examples
2002    ///
2003    /// ```rust, no_run
2004    /// # {before_snippet}
2005    /// use esp_hal::uart::{Config, Uart};
2006    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
2007    ///
2008    /// const MESSAGE: &[u8] = b"Hello, world!";
2009    /// uart.write(&MESSAGE)?;
2010    /// # {after_snippet}
2011    /// ```
2012    ///
2013    /// # Errors
2014    ///
2015    /// [`TxError`] when an error occurred during the write operation
2016    pub fn write(&mut self, data: &[u8]) -> Result<usize, TxError> {
2017        self.tx.write(data)
2018    }
2019
2020    #[procmacros::doc_replace]
2021    /// Flushes the transmit buffer of the UART.
2022    ///
2023    /// # Examples
2024    ///
2025    /// ```rust, no_run
2026    /// # {before_snippet}
2027    /// use esp_hal::uart::{Config, Uart};
2028    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
2029    ///
2030    /// const MESSAGE: &[u8] = b"Hello, world!";
2031    /// uart.write(&MESSAGE)?;
2032    /// uart.flush()?;
2033    /// # {after_snippet}
2034    /// ```
2035    pub fn flush(&mut self) -> Result<(), TxError> {
2036        self.tx.flush()
2037    }
2038
2039    /// Sends a break signal for a specified duration.
2040    #[instability::unstable]
2041    pub fn send_break(&mut self, bits: u32) {
2042        self.tx.send_break(bits)
2043    }
2044
2045    #[procmacros::doc_replace]
2046    /// Returns whether the UART receive buffer has at least one byte of data.
2047    ///
2048    /// If this function returns `true`, [`Self::read`] and [`Self::read_async`]
2049    /// will not block. Otherwise, they will not return until data is available.
2050    ///
2051    /// Data that does not get stored due to an error will be lost and does not count
2052    /// towards the number of bytes in the receive buffer.
2053    // TODO: once we add support for UART_ERR_WR_MASK it needs to be documented here.
2054    /// # Examples
2055    ///
2056    /// ```rust, no_run
2057    /// # {before_snippet}
2058    /// use esp_hal::uart::{Config, Uart};
2059    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
2060    ///
2061    /// while !uart.read_ready() {
2062    ///     // Do something else while waiting for data to be available.
2063    /// }
2064    ///
2065    /// let mut buf = [0u8; 32];
2066    /// uart.read(&mut buf[..])?;
2067    ///
2068    /// # {after_snippet}
2069    /// ```
2070    pub fn read_ready(&self) -> bool {
2071        self.rx.read_ready()
2072    }
2073
2074    /// Returns whether a break condition has been detected.
2075    ///
2076    /// The returned status is sticky and remains set until
2077    /// [`Self::clear_break_detected`] is called, or until one of the
2078    /// `wait_for_break` methods observes and clears it.
2079    #[instability::unstable]
2080    pub fn is_break_detected(&self) -> bool {
2081        self.rx.is_break_detected()
2082    }
2083
2084    /// Clears the break-detection status.
2085    #[instability::unstable]
2086    pub fn clear_break_detected(&mut self) {
2087        self.rx.clear_break_detected();
2088    }
2089
2090    #[procmacros::doc_replace]
2091    /// Reads received bytes.
2092    ///
2093    /// The UART hardware continuously receives bytes and stores them in the RX
2094    /// FIFO. Reads the bytes from the RX FIFO and returns them in the provided
2095    /// buffer. If the hardware buffer is empty, blocks until data is available.
2096    /// [`Self::read_ready`] can be used to check if data is available without
2097    /// blocking.
2098    ///
2099    /// Returns the number of bytes read into the buffer. This may be less than
2100    /// the length of the buffer. Returns 0 only if the provided buffer is empty.
2101    ///
2102    /// # Examples
2103    ///
2104    /// ```rust, no_run
2105    /// # {before_snippet}
2106    /// use esp_hal::uart::{Config, Uart};
2107    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
2108    ///
2109    /// const MESSAGE: &[u8] = b"Hello, world!";
2110    /// uart.write(&MESSAGE)?;
2111    /// uart.flush()?;
2112    ///
2113    /// let mut buf = [0u8; MESSAGE.len()];
2114    /// uart.read(&mut buf[..])?;
2115    ///
2116    /// # {after_snippet}
2117    /// ```
2118    ///
2119    /// # Errors
2120    ///
2121    /// [`RxError`] when a reported error occurred since
2122    /// the last check for errors.
2123    ///
2124    /// If the error occurred before this function was called, the contents of
2125    /// the FIFO are not modified.
2126    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
2127        self.rx.read(buf)
2128    }
2129
2130    #[procmacros::doc_replace(
2131        "unsent_data" => {
2132            cfg(esp32) => "On `UART0`, the function discards the data that the transmitter did not send yet, and the TX line goes low for a short time. A receiver reports that pulse as an error. On `UART1` and `UART2`, the transmitter sends that data with the new configuration, and a receiver can get corrupted data.",
2133            _ => "The function discards the data that the transmitter did not send yet, and the TX line goes low for a short time. A receiver reports that pulse as an error."
2134        }
2135    )]
2136    /// Changes the configuration.
2137    ///
2138    /// Do not call this function while a transmission is in progress.
2139    /// __unsent_data__
2140    /// Call [`Self::flush`] first, to let the transmitter send the remaining data.
2141    ///
2142    /// # Examples
2143    ///
2144    /// ```rust, no_run
2145    /// # {before_snippet}
2146    /// use esp_hal::uart::{Config, Uart};
2147    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?;
2148    ///
2149    /// uart.apply_config(&Config::default().with_baudrate(19_200))?;
2150    /// # {after_snippet}
2151    /// ```
2152    ///
2153    /// # Errors
2154    ///
2155    /// [`ConfigError`] when the configuration is not supported by the hardware
2156    pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> {
2157        // Must apply the common settings first, as `rx.apply_config` reads back symbol
2158        // size.
2159        self.rx.uart.info().apply_config(config)?;
2160        // `send_break` calculates the break duration from this value.
2161        self.tx.baudrate = config.baudrate;
2162
2163        self.rx.apply_config(config)?;
2164        self.tx.apply_config(config)?;
2165        Ok(())
2166    }
2167
2168    /// Lets activity on the RX line wake the chip from light sleep.
2169    ///
2170    /// See [`UartRx::enable_wakeup`].
2171    ///
2172    /// # Errors
2173    ///
2174    /// [`WakeConfigError::NotAWakeupSource`] when this UART instance cannot wake the chip,
2175    /// and [`WakeConfigError::EdgeCountUnsupported`] when the hardware cannot count the requested
2176    /// number of edges.
2177    #[cfg(sleep_driver_supported)]
2178    #[instability::unstable]
2179    pub fn enable_wakeup(&mut self, config: &WakeupConfig) -> Result<(), WakeConfigError> {
2180        self.rx.enable_wakeup(config)
2181    }
2182
2183    /// Stops the UART from waking the chip.
2184    #[cfg(sleep_driver_supported)]
2185    #[instability::unstable]
2186    pub fn disable_wakeup(&mut self) {
2187        self.rx.disable_wakeup();
2188    }
2189
2190    #[procmacros::doc_replace]
2191    /// Splits the UART into a transmitter and receiver.
2192    ///
2193    /// This is particularly useful when having two tasks correlating to
2194    /// transmitting and receiving.
2195    ///
2196    /// # Examples
2197    ///
2198    /// ```rust, no_run
2199    /// # {before_snippet}
2200    /// use esp_hal::uart::{Config, Uart};
2201    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
2202    ///     .with_rx(peripherals.GPIO1)
2203    ///     .with_tx(peripherals.GPIO2);
2204    ///
2205    /// // The UART can be split into separate Transmit and Receive components:
2206    /// let (mut rx, mut tx) = uart.split();
2207    ///
2208    /// // Each component can be used individually to interact with the UART:
2209    /// tx.write(&[42u8])?;
2210    /// let mut byte = [0u8; 1];
2211    /// rx.read(&mut byte);
2212    /// # {after_snippet}
2213    /// ```
2214    #[instability::unstable]
2215    pub fn split(self) -> (UartRx<'d, Dm>, UartTx<'d, Dm>) {
2216        (self.rx, self.tx)
2217    }
2218
2219    #[procmacros::doc_replace]
2220    /// Borrows the UART as separate transmitter and receiver halves.
2221    ///
2222    /// Unlike [`split`], this method does not consume the UART. The returned
2223    /// transmitter and receiver are borrowed from the original UART, which can
2224    /// be used again after those borrows end.
2225    ///
2226    /// This is particularly useful when running separate transmit and receive
2227    /// futures concurrently.
2228    ///
2229    /// # Examples
2230    ///
2231    /// ```rust, no_run
2232    /// # {before_snippet}
2233    /// use esp_hal::uart::{Config, Uart};
2234    /// let mut uart = Uart::new(peripherals.UART0, Config::default())?
2235    ///     .with_rx(peripherals.GPIO1)
2236    ///     .with_tx(peripherals.GPIO2);
2237    ///
2238    /// loop {
2239    ///     // The UART can be split into separate Transmit and Receive components:
2240    ///     let (rx, tx) = uart.split_mut();
2241    ///
2242    ///     // Each component can be used individually to interact with the UART:
2243    ///     tx.write(&[42u8])?;
2244    ///     let mut byte = [0u8; 1];
2245    ///     rx.read(&mut byte);
2246    /// }
2247    /// # {after_snippet}
2248    /// ```
2249    #[instability::unstable]
2250    pub fn split_mut(&mut self) -> (&mut UartRx<'d, Dm>, &mut UartTx<'d, Dm>) {
2251        (&mut self.rx, &mut self.tx)
2252    }
2253
2254    /// Reads and clears RX error conditions set by received data.
2255    ///
2256    /// Only errors enabled in [`RxConfig::with_reported_errors`] are returned;
2257    /// disabled errors are cleared and ignored.
2258    #[instability::unstable]
2259    pub fn check_for_rx_errors(&mut self) -> Result<(), RxError> {
2260        self.rx.check_for_errors()
2261    }
2262
2263    /// Reads already received bytes.
2264    ///
2265    /// Reads the already received bytes from the FIFO into the provided buffer.
2266    /// Does not wait for the FIFO to actually contain any bytes.
2267    ///
2268    /// Returns the number of bytes read into the buffer. This may be less than
2269    /// the length of the buffer, and it may also be 0.
2270    ///
2271    /// # Errors
2272    ///
2273    /// [`RxError`] when a reported error occurred since
2274    /// the last check for errors.
2275    ///
2276    /// If the error occurred before this function was called, the contents of
2277    /// the FIFO are not modified.
2278    #[instability::unstable]
2279    pub fn read_buffered(&mut self, buf: &mut [u8]) -> Result<usize, RxError> {
2280        self.rx.read_buffered(buf)
2281    }
2282
2283    /// Configures the AT-CMD detection settings.
2284    #[instability::unstable]
2285    pub fn set_at_cmd(&mut self, config: AtCmdConfig) {
2286        #[cfg(uart_has_sclk_enable)]
2287        self.rx.uart.info().set_at_cmd_clock_enabled(false);
2288
2289        self.regs().at_cmd_char().write(|w| unsafe {
2290            w.at_cmd_char().bits(config.cmd_char);
2291            w.char_num().bits(config.char_num)
2292        });
2293
2294        if let Some(pre_idle_count) = config.pre_idle_count {
2295            self.regs()
2296                .at_cmd_precnt()
2297                .write(|w| unsafe { w.pre_idle_num().bits(pre_idle_count as _) });
2298        }
2299
2300        if let Some(post_idle_count) = config.post_idle_count {
2301            self.regs()
2302                .at_cmd_postcnt()
2303                .write(|w| unsafe { w.post_idle_num().bits(post_idle_count as _) });
2304        }
2305
2306        if let Some(gap_timeout) = config.gap_timeout {
2307            self.regs()
2308                .at_cmd_gaptout()
2309                .write(|w| unsafe { w.rx_gap_tout().bits(gap_timeout as _) });
2310        }
2311
2312        #[cfg(uart_has_sclk_enable)]
2313        self.rx.uart.info().set_at_cmd_clock_enabled(true);
2314
2315        sync_regs(self.regs());
2316    }
2317
2318    #[inline(always)]
2319    fn init(&mut self, config: Config) -> Result<(), ConfigError> {
2320        self.rx.disable_rx_interrupts();
2321        self.tx.disable_tx_interrupts();
2322
2323        enable_register_sync(self.regs());
2324
2325        // Applying the config also empties the RX FIFO, and resets the TX FIFO where the
2326        // hardware can.
2327        self.apply_config(&config)?;
2328
2329        // Don't wait after transmissions by default,
2330        // so that bytes written to TX FIFO are always immediately transmitted.
2331        self.regs()
2332            .idle_conf()
2333            .modify(|_, w| unsafe { w.tx_idle_num().bits(0) });
2334        // `idle_conf` is a sync register.
2335        sync_regs(self.regs());
2336
2337        crate::rom::ets_delay_us(15);
2338
2339        // Make sure we are starting in a "clean state" - previous operations might have
2340        // run into error conditions
2341        self.regs().int_clr().write(|w| unsafe { w.bits(u32::MAX) });
2342
2343        Ok(())
2344    }
2345}
2346
2347/// UART Tx or Rx Error.
2348#[instability::unstable]
2349#[derive(Debug, Clone, Copy, PartialEq)]
2350#[cfg_attr(feature = "defmt", derive(defmt::Format))]
2351#[non_exhaustive]
2352pub enum IoError {
2353    /// UART TX error.
2354    Tx(TxError),
2355    /// UART RX error.
2356    Rx(RxError),
2357}
2358
2359#[instability::unstable]
2360impl core::error::Error for IoError {}
2361
2362#[instability::unstable]
2363impl core::fmt::Display for IoError {
2364    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2365        match self {
2366            IoError::Tx(e) => e.fmt(f),
2367            IoError::Rx(e) => e.fmt(f),
2368        }
2369    }
2370}
2371
2372#[instability::unstable]
2373impl From<RxError> for IoError {
2374    fn from(e: RxError) -> Self {
2375        IoError::Rx(e)
2376    }
2377}
2378
2379#[instability::unstable]
2380impl From<TxError> for IoError {
2381    fn from(e: TxError) -> Self {
2382        IoError::Tx(e)
2383    }
2384}