Skip to main content

nrf52/
uart.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022-2026.
4
5//! Universal asynchronous receiver/transmitter (UART)
6//!
7//! This is the legacy, non-EasyDMA UART peripheral. It shares the same
8//! peripheral instance (and MMIO address) as the UARTE peripheral
9//! ([`crate::uarte::Uarte`]), so a chip can use one or the other but not both
10//! at the same time.
11//!
12//! This driver only implements a synchronous, polling transmit path, and does
13//! not use interrupts or implement [`kernel::hil::uart::Transmit`] or
14//! [`kernel::hil::uart::Receive`]. It exists solely to back a
15//! [`kernel::platform::chip::PanicWriter`] for boards that want to print
16//! panic messages over this peripheral.
17//!
18//! See the nRF52840 Product Specification, UART chapter, for details:
19//! <https://docs.nordicsemi.com/r/bundle/ps_nrf52840/page/uart.html>
20
21use kernel::ErrorCode;
22use kernel::hil::uart;
23use kernel::utilities::StaticRef;
24use kernel::utilities::io_write::IoWrite;
25use nrf5x::gpio::Pin;
26use tock_registers_v0::interfaces::{Readable, Writeable};
27use tock_registers_v0::registers::{ReadWrite, WriteOnly};
28use tock_registers_v0::{register_bitfields, register_structs};
29
30pub const UART0_BASE: StaticRef<UartRegisters> =
31    unsafe { StaticRef::new(0x40002000 as *const UartRegisters) };
32
33register_structs! {
34    pub UartRegisters {
35        (0x000 => _reserved1),
36        (0x004 => task_stoprx: WriteOnly<u32, Task::Register>),
37        (0x008 => task_starttx: WriteOnly<u32, Task::Register>),
38        (0x00C => task_stoptx: WriteOnly<u32, Task::Register>),
39        (0x010 => _reserved2),
40        (0x11C => event_txdrdy: ReadWrite<u32, Event::Register>),
41        (0x120 => _reserved3),
42        (0x500 => enable: ReadWrite<u32, Enable::Register>),
43        (0x504 => _reserved4),
44        (0x508 => pselrts: ReadWrite<u32, Psel::Register>),
45        (0x50C => pseltxd: ReadWrite<u32, Psel::Register>),
46        (0x510 => pselcts: ReadWrite<u32, Psel::Register>),
47        (0x514 => pselrxd: ReadWrite<u32, Psel::Register>),
48        (0x518 => _reserved5),
49        (0x51C => txd: WriteOnly<u32, Byte::Register>),
50        (0x520 => _reserved6),
51        (0x524 => baudrate: ReadWrite<u32, Baudrate::Register>),
52        (0x528 => _reserved7),
53        (0x56C => config: ReadWrite<u32, Config::Register>),
54        (0x570 => @END),
55    }
56}
57
58register_bitfields! [u32,
59    /// Start task
60    Task [
61        ENABLE OFFSET(0) NUMBITS(1)
62    ],
63
64    /// Read event
65    Event [
66        READY OFFSET(0) NUMBITS(1)
67    ],
68
69    /// Enable UART
70    Enable [
71        ENABLE OFFSET(0) NUMBITS(4) [
72            ON = 4,
73            OFF = 0
74        ]
75    ],
76
77    /// Pin select
78    Psel [
79        // Pin number. MSB is actually the port indicator, but since we number
80        // pins sequentially the binary representation of the pin number has
81        // the port bit set correctly. So, for simplicity we just treat the
82        // pin number as a 6 bit field.
83        PIN OFFSET(0) NUMBITS(6) [],
84        // Connect/Disconnect
85        CONNECT OFFSET(31) NUMBITS(1) [
86            Disconnected = 1,
87            Connected = 0,
88        ]
89    ],
90
91    /// A single data byte sent or received over the wire
92    Byte [
93        VALUE OFFSET(0) NUMBITS(8)
94    ],
95
96    /// Baudrate
97    Baudrate [
98        BAUDRATE OFFSET(0) NUMBITS(32)
99    ],
100
101    /// Configuration of parity and flow control
102    Config [
103        HWFC OFFSET(0) NUMBITS(1),
104        PARITY OFFSET(1) NUMBITS(3)
105    ]
106];
107
108/// UART driver
109pub struct Uart {
110    registers: StaticRef<UartRegisters>,
111}
112
113impl Uart {
114    pub fn new(regs: StaticRef<UartRegisters>) -> Uart {
115        Uart { registers: regs }
116    }
117
118    fn initialize(&self, txd: Pin, rxd: Pin, cts: Option<Pin>, rts: Option<Pin>) {
119        self.disable_uart_and_uarte();
120
121        // Stop any ongoing TX or RX sequences.
122        self.registers.task_stoptx.write(Task::ENABLE::SET);
123        self.registers.task_stoprx.write(Task::ENABLE::SET);
124
125        // Make sure we clear the txdrdy event in case it was set from the UARTE
126        // version of the peripheral.
127        self.registers.event_txdrdy.write(Event::READY::CLEAR);
128
129        self.registers.pseltxd.write(Psel::PIN.val(txd as _));
130        self.registers.pselrxd.write(Psel::PIN.val(rxd as _));
131        if let Some(cts_pin) = cts {
132            self.registers.pselcts.write(Psel::PIN.val(cts_pin as _));
133        } else {
134            // If no CTS pin is provided, then we need to mark it as
135            // disconnected in the register.
136            self.registers.pselcts.write(Psel::CONNECT::Disconnected);
137        }
138        if let Some(rts_pin) = rts {
139            self.registers.pselrts.write(Psel::PIN.val(rts_pin as _));
140        } else {
141            // If no RTS pin is provided, then we need to mark it as
142            // disconnected in the register.
143            self.registers.pselrts.write(Psel::CONNECT::Disconnected);
144        }
145
146        self.enable_uart();
147    }
148
149    fn set_baud_rate(&self, baud_rate: u32) -> Result<(), ErrorCode> {
150        let divider = crate::uarte::Uarte::get_divider_for_baud(baud_rate)?;
151        self.registers.baudrate.set(divider);
152
153        Ok(())
154    }
155
156    fn enable_uart(&self) {
157        self.registers.enable.write(Enable::ENABLE::ON);
158    }
159
160    /// The UART and UARTE peripherals alias. There is no way to turn off one
161    /// without turning off both of them.
162    fn disable_uart_and_uarte(&self) {
163        self.registers.enable.write(Enable::ENABLE::OFF);
164    }
165
166    /// Transmit one byte and block until completion. This is used by the panic handler.
167    pub fn send_byte(&self, byte: u8) {
168        self.registers.event_txdrdy.write(Event::READY::CLEAR);
169        self.registers.txd.write(Byte::VALUE.val(byte as u32));
170        self.registers.task_starttx.write(Task::ENABLE::SET);
171
172        while !self.registers.event_txdrdy.is_set(Event::READY) {}
173    }
174}
175
176impl uart::Configure for Uart {
177    fn configure(&self, params: uart::Parameters) -> Result<(), ErrorCode> {
178        self.set_baud_rate(params.baud_rate)?;
179
180        // These could probably be implemented, but are currently ignored, so
181        // throw an error.
182        if params.stop_bits != uart::StopBits::One {
183            return Err(ErrorCode::NOSUPPORT);
184        }
185        if params.parity != uart::Parity::None {
186            return Err(ErrorCode::NOSUPPORT);
187        }
188        if params.hw_flow_control {
189            return Err(ErrorCode::NOSUPPORT);
190        }
191
192        Ok(())
193    }
194}
195
196/// A synchronous writer for the nRF52 useful for panics.
197///
198/// For boards that want to use the UART to display panic messages, this
199/// provides an implementation of
200/// [`PanicWriter`](kernel::platform::chip::PanicWriter) with synchronous
201/// output.
202///
203/// This is only to be used by panic messages and is not used within the normal
204/// operation of the Tock kernel.
205struct UartPanicWriter {
206    inner: Uart,
207}
208
209impl IoWrite for UartPanicWriter {
210    fn write(&mut self, buf: &[u8]) -> usize {
211        for &c in buf {
212            self.inner.send_byte(c);
213        }
214        buf.len()
215    }
216}
217
218impl core::fmt::Write for UartPanicWriter {
219    fn write_str(&mut self, s: &str) -> core::fmt::Result {
220        self.write(s.as_bytes());
221        Ok(())
222    }
223}
224
225/// Configuration for the synchronous UART panic writer.
226///
227/// This captures everything needed to setup the UART for panic display, even
228/// if the normal kernel had initialized it differently.
229pub struct UartPanicWriterConfig {
230    pub params: uart::Parameters,
231    pub txd: Pin,
232    pub rxd: Pin,
233    pub cts: Option<Pin>,
234    pub rts: Option<Pin>,
235}
236
237impl kernel::platform::chip::PanicWriter for Uart {
238    type Config = UartPanicWriterConfig;
239
240    fn create_panic_writer(
241        config: Self::Config,
242        _panic: &core::panic::PanicInfo,
243    ) -> impl IoWrite + core::fmt::Write {
244        use uart::Configure as _;
245
246        let inner = Uart::new(UART0_BASE);
247        inner.initialize(config.txd, config.rxd, config.cts, config.rts);
248        let _ = inner.configure(config.params);
249        UartPanicWriter { inner }
250    }
251}