Universal Asynchronous Receiver/Transmitter (UART)
Overview
RTL8721F provides up to four UART peripherals for asynchronous serial communication. The Rust driver ameba_hal::uart wraps the PAC register block directly — no raw bit-masking or C FFI is involved.
Features
Up to four peripheral instances,
Uart0throughUart3, all implementing the sharedUartInstancetraitConfigurable baud rate, 7 or 8 data bits via
DataBits::_7/DataBits::_8, no/odd/even parity viaParity::None/Parity::Odd/Parity::Even, and 1 or 2 stop bits viaStopBits::One/StopBits::TwoOptional RTS/CTS hardware flow control via
FlowControl::RtsCtsInternal hardware loopback via
loopback_cmd, used by every bundled example to avoid external wiringForced RTS output override via
rts_force_cmd, independent of the auto-flow-control pathConfigurable Rx timeout and Rx-FIFO-empty timeout thresholds via
rx_to_thres_config/rx_reti_thres_configConfigurable Rx debounce filter via
rx_debounce_config/rx_debounce_cmdIrDA SIR interface with pulse-shift and Rx-filter configuration via
irda_init/irda_cmdLP Rx baud-rate monitor for auto-detecting the peer’s baud rate via
monitor_para_config/lp_rx_baud_set/rx_monitor_cmdRaw interrupt callback registration via
register_irq/UartIrqHandler, independent of the async waker pathOperation mode:
Blocking: poll-driven, implements
embedded_io::Read/embedded_io::WriteAsync: interrupt-driven via an
embassywaker, implementsembedded_io_async::Read/embedded_io_async::WriteDMA: GDMA-backed transfer via
into_dma_async, using twoDmaChannelinstances for TX and RX
Note
Async slave-mode operation is not exposed by the driver’s public API. GDMA-backed transfers require a pair of DmaChannel handles obtained separately from the DMA driver.
Operating Modes
UART supports four operating modes: Blocking Mode, Async Mode, DMA Mode, and Interrupt Mode.
Blocking Mode
The CPU polls the UART status registers and reads or writes the FIFO buffer as needed. This is the default mode returned by Uart::steal(), and implements embedded_io::Read / embedded_io::Write.
Suited for simple, low-frequency transfers where blocking the current task is acceptable.
use embedded_io::{Read, Write};
...
use ameba_hal::uart::{Uart, Uart0, UartConfig};
...
let mut uart = unsafe { Uart::<Uart0>::steal() };
uart.init(&UartConfig::default());
uart.loopback_cmd(true);
...
let _ = uart.write(&tx);
// Drain RX loopback bytes - blocks on first byte, then reads available
let mut rx = [0u8; 4];
let mut got = 0usize;
while got < 4 {
match uart.read(&mut rx[got..]) {
Ok(n) => got += n,
Err(_) => break,
}
}
Full example: examples/uart/blocking/src/main.rs.
Async Mode
Interrupt-driven transfers built on the Embassy waker mechanism, obtained by calling into_async on an enabled blocking instance. Implements embedded_io_async::Read / embedded_io_async::Write, so the current async task yields instead of busy-polling while a transfer is in flight.
use ameba_hal::Async;
use ameba_hal::uart::{InterruptHandler, Uart, Uart0, UartConfig};
...
ameba_hal::bind_interrupts!(struct Irqs {
UART0_IRQ => InterruptHandler<Uart0>;
});
...
let uart = unsafe { Uart::<Uart0>::steal() };
uart.init(&UartConfig::default());
uart.loopback_cmd(true);
let uart_async = uart.into_async(Irqs);
...
let _ = uart.write(&tx).await;
...
let result = embassy_time::with_timeout(
Duration::from_millis(500),
uart.read(&mut rx),
).await;
Full example: examples/uart/async/src/main.rs.
DMA Mode
GDMA-backed transfer, obtained by calling into_dma_async on an enabled blocking instance with a pair of DmaChannel handles for TX and RX. Suited for large buffers, since the CPU only sets up the transfer and awaits completion instead of touching the FIFO byte by byte.
use ameba_hal::dma::{Blocking, DmaChannel};
use ameba_hal::uart::{Uart, Uart0, UartConfig, UartDma};
...
let uart = unsafe { Uart::<Uart0>::steal() };
uart.init(&UartConfig::default());
uart.loopback_cmd(true);
// into_dma_async configures FCR DMA mode, burst sizes, and enables NVIC IRQs.
let mut uart_dma: UartDma<Uart0, 0, 1> = uart.into_dma_async(
unsafe { DmaChannel::<0, Blocking>::steal() },
unsafe { DmaChannel::<1, Blocking>::steal() },
);
...
match embassy_time::with_timeout(
Duration::from_millis(500),
uart_dma.dma_transfer(tx_slice, rx_slice),
).await {
Ok(()) => {
println!("[UART DMA] transfer done");
}
Err(_) => {
println!("[FAIL] UART DMA: timeout");
loop { Timer::after(Duration::from_secs(1)).await; }
}
}
Full example: examples/uart/dma/src/main.rs. UartDma also exposes dma_write and dma_read for one-directional transfers.
Interrupt Mode
A user-registered raw ISR callback, obtained by calling register_irq on a blocking instance. Unlike Async Mode, the callback runs directly in the UART’s NVIC interrupt context via the UartIrqHandler trait, independent of the Embassy waker/executor path, which is useful when the main loop only writes and all receiving is handled from the ISR.
use core::ptr::addr_of_mut;
use core::sync::atomic::{AtomicU32, Ordering};
...
use ameba_hal::uart::{
InterruptHandler, UART0_PTR, Uart, Uart0, UartConfig, UartIrqEvent, UartIrqHandler, read_available,
};
...
ameba_hal::bind_interrupts!(struct Irqs {
UART0_IRQ => InterruptHandler<Uart0>;
});
struct RxCounter {
bytes: AtomicU32,
}
impl UartIrqHandler for RxCounter {
fn on_irq(&mut self, event: UartIrqEvent) {
if event.rx_error {
println!("[UART-IRQ] rx error lsr=0x{:04X} (from ISR)", event.lsr);
return;
}
let mut buf = [0u8; 16];
let n = unsafe { read_available(UART0_PTR, &mut buf) };
self.bytes.fetch_add(n as u32, Ordering::Relaxed);
println!("[UART-IRQ] rx {} byte(s): {:02X?} (from ISR)", n, &buf[..n]);
}
}
static mut RX_COUNTER: RxCounter = RxCounter { bytes: AtomicU32::new(0) };
...
let mut uart = unsafe { Uart::<Uart0>::steal() };
uart.init(&UartConfig::default());
uart.loopback_cmd(true);
let handler = unsafe { &mut *addr_of_mut!(RX_COUNTER) };
uart.register_irq(handler, Irqs);
Full example: examples/uart/interrupt/src/main.rs.
Application Examples
The Rust SDK provides four example projects under examples/uart/:
-
UART0, blocking mode, internal hardware loopback. Sends 3 rounds of 4 bytes, blocking-reads them back, and compares.
Wiring: none — uses UART0 internal loopback (
loopback_cmd(true)).[UART BLK] start [UART BLK] round 1 sent:[41424301] recv:[41424301] [UART BLK] round 2 sent:[42434402] recv:[42434402] [UART BLK] round 3 sent:[43444503] recv:[43444503] [PASS] UART blocking: OK
-
UART0, async mode, internal hardware loopback. Phase 1 runs 3 rounds of 4-byte echo with a 500 ms timeout. Phase 2 writes 256 bytes while a concurrent heartbeat task confirms the executor is not blocked.
Wiring: none — uses UART0 internal loopback.
[UART ASYNC] start [UART ASYNC] round 1 tx=[41 42 43 01] rx=[41 42 43 01] OK ... [PASS] UART async: echo OK [UART] concurrent: 256B write start [UART] heartbeats seen: N [PASS] UART async: non-blocking write OK [HB] N ...
The heartbeat task keeps printing
[HB] Nlines after the final[PASS]. -
UART0, DMA mode, internal hardware loopback. Transfers 256 bytes concurrently via GDMA channel 0 (TX) and channel 1 (RX), then verifies the received buffer matches the transmitted pattern.
Wiring: none — uses UART0 internal loopback.
[UART DMA] start [UART DMA] transfer done [PASS] UART DMA: 256 bytes loopback OK
-
UART0, internal hardware loopback. Registers a raw ISR callback via
register_irqthat drains and logs the Rx FIFO directly from interrupt context, independent of the async waker path used byuart/async. The main loop blocking-sends 5 rounds of 4 bytes. All receiving happens inside the ISR.Wiring: none — uses UART0 internal loopback.
[UART interrupt] start [UART] [1] sent [41, 42, 43, 01] [UART-IRQ] rx 1 byte(s): [41] (from ISR) [UART-IRQ] rx 3 byte(s): [42, 43, 01] (from ISR) ... [PASS] UART interrupt: 20 bytes echoed via ISR OK
The 4 bytes of one round are not always received in a single ISR call; they may be split across several
[UART-IRQ]lines, so the split shown above can differ from run to run.
Note
Build any example with cargo xtask build example --name uart/<demo>.
API Reference
Quick Usage
use ameba_hal::uart::{Uart, Uart0, UartConfig};
use embedded_io::{Read, Write};
let mut uart = unsafe { Uart::<Uart0>::steal() };
uart.init(&UartConfig::default());
let _ = uart.write(&[0x42u8]);
let mut rx = [0u8; 4];
let _ = uart.read(&mut rx);
Uart also implements embedded_io_async::Read / embedded_io_async::Write once converted with into_async, and exposes DMA-backed transfer via into_dma_async — see the Operating Modes section above.