embassy/embassy-nrf/src/uarte.rs

414 lines
12 KiB
Rust
Raw Normal View History

2020-12-23 16:18:29 +01:00
//! Async low power UARTE.
//!
//! The peripheral is automatically enabled and disabled as required to save power.
//! Lowest power consumption can only be guaranteed if the send receive futures
//! are dropped correctly (e.g. not using `mem::forget()`).
use core::future::Future;
2021-03-22 01:15:44 +01:00
use core::marker::PhantomData;
use core::pin::Pin;
2020-12-23 16:18:29 +01:00
use core::sync::atomic::{compiler_fence, Ordering};
2021-03-22 01:15:44 +01:00
use core::task::Poll;
use embassy::traits::uart::{Error, Read, Write};
use embassy::util::{wake_on_interrupt, OnDrop, PeripheralBorrow, Signal};
use embassy_extras::unborrow;
use futures::future::poll_fn;
2020-12-23 16:18:29 +01:00
use crate::fmt::{assert, *};
2021-03-22 01:15:44 +01:00
use crate::gpio::Pin as GpioPin;
2020-12-23 16:18:29 +01:00
use crate::hal::pac;
use crate::hal::target_constants::EASY_DMA_SIZE;
2021-03-08 00:15:40 +01:00
use crate::interrupt;
use crate::interrupt::Interrupt;
2021-03-22 01:15:44 +01:00
use crate::peripherals;
2020-12-23 16:18:29 +01:00
// Re-export SVD variants to allow user to directly set values.
pub use pac::uarte0::{baudrate::BAUDRATE_A as Baudrate, config::PARITY_A as Parity};
2021-03-22 01:15:44 +01:00
#[non_exhaustive]
pub struct Config {
pub parity: Parity,
pub baudrate: Baudrate,
2020-12-23 16:18:29 +01:00
}
2021-03-22 01:15:44 +01:00
impl Default for Config {
fn default() -> Self {
Self {
parity: Parity::EXCLUDED,
baudrate: Baudrate::BAUD115200,
}
}
2020-12-23 16:18:29 +01:00
}
2021-03-22 01:15:44 +01:00
/// Interface to the UARTE peripheral
pub struct Uarte<'d, T: Instance> {
peri: T,
irq: T::Interrupt,
phantom: PhantomData<&'d mut T>,
}
impl<'d, T: Instance> Uarte<'d, T> {
2020-12-23 16:18:29 +01:00
/// Creates the interface to a UARTE instance.
/// Sets the baud rate, parity and assigns the pins to the UARTE peripheral.
///
2021-03-08 00:15:40 +01:00
/// # Safety
2020-12-23 16:18:29 +01:00
///
/// The returned API is safe unless you use `mem::forget` (or similar safe mechanisms)
/// on stack allocated buffers which which have been passed to [`send()`](Uarte::send)
/// or [`receive`](Uarte::receive).
#[allow(unused_unsafe)]
pub unsafe fn new(
2021-03-22 01:15:44 +01:00
uarte: impl PeripheralBorrow<Target = T> + 'd,
irq: impl PeripheralBorrow<Target = T::Interrupt> + 'd,
rxd: impl PeripheralBorrow<Target = impl GpioPin> + 'd,
txd: impl PeripheralBorrow<Target = impl GpioPin> + 'd,
cts: impl PeripheralBorrow<Target = impl GpioPin> + 'd,
rts: impl PeripheralBorrow<Target = impl GpioPin> + 'd,
config: Config,
2020-12-23 16:18:29 +01:00
) -> Self {
2021-03-22 01:15:44 +01:00
unborrow!(uarte, irq, rxd, txd, cts, rts);
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
let r = uarte.regs();
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
assert!(r.enable.read().enable().is_disabled());
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
// TODO OptionalPin for RTS/CTS.
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
txd.set_high();
rts.set_high();
rxd.conf().write(|w| w.input().connect().drive().h0h1());
txd.conf().write(|w| w.dir().output().drive().h0h1());
//cts.conf().write(|w| w.input().connect().drive().h0h1());
//rts.conf().write(|w| w.dir().output().drive().h0h1());
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
r.psel.rxd.write(|w| unsafe { w.bits(rxd.psel_bits()) });
r.psel.txd.write(|w| unsafe { w.bits(txd.psel_bits()) });
//r.psel.cts.write(|w| unsafe { w.bits(cts.psel_bits()) });
//r.psel.rts.write(|w| unsafe { w.bits(rts.psel_bits()) });
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
r.baudrate.write(|w| w.baudrate().variant(config.baudrate));
r.config.write(|w| w.parity().variant(config.parity));
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
// Enable
r.enable.write(|w| w.enable().enabled());
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
Self {
peri: uarte,
irq,
phantom: PhantomData,
}
2020-12-23 16:18:29 +01:00
}
2021-03-22 01:15:44 +01:00
/*
unsafe fn on_irq(_ctx: *mut ()) {
2020-12-23 16:18:29 +01:00
let uarte = &*pac::UARTE0::ptr();
let mut try_disable = false;
if uarte.events_endtx.read().bits() != 0 {
uarte.events_endtx.reset();
trace!("endtx");
compiler_fence(Ordering::SeqCst);
if uarte.events_txstarted.read().bits() != 0 {
// The ENDTX was signal triggered because DMA has finished.
uarte.events_txstarted.reset();
try_disable = true;
}
2020-12-23 16:18:29 +01:00
T::state().tx_done.signal(());
}
if uarte.events_txstopped.read().bits() != 0 {
uarte.events_txstopped.reset();
trace!("txstopped");
try_disable = true;
}
if uarte.events_endrx.read().bits() != 0 {
uarte.events_endrx.reset();
trace!("endrx");
let len = uarte.rxd.amount.read().bits();
compiler_fence(Ordering::SeqCst);
if uarte.events_rxstarted.read().bits() != 0 {
// The ENDRX was signal triggered because DMA buffer is full.
uarte.events_rxstarted.reset();
try_disable = true;
}
2020-12-23 16:18:29 +01:00
T::state().rx_done.signal(len);
}
if uarte.events_rxto.read().bits() != 0 {
uarte.events_rxto.reset();
trace!("rxto");
try_disable = true;
}
// Disable the peripheral if not active.
if try_disable
&& uarte.events_txstarted.read().bits() == 0
&& uarte.events_rxstarted.read().bits() == 0
{
trace!("disable");
uarte.enable.write(|w| w.enable().disabled());
}
}
2021-03-22 01:15:44 +01:00
*/
2020-12-23 16:18:29 +01:00
}
2021-03-22 01:15:44 +01:00
impl<'d, T: Instance> Read for Uarte<'d, T> {
#[rustfmt::skip]
type ReadFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a;
2021-01-02 19:59:37 +01:00
2021-03-22 01:15:44 +01:00
fn read<'a>(self: Pin<&'a mut Self>, rx_buffer: &'a mut [u8]) -> Self::ReadFuture<'a> {
async move {
let this = unsafe { self.get_unchecked_mut() };
let ptr = rx_buffer.as_ptr();
let len = rx_buffer.len();
assert!(len <= EASY_DMA_SIZE);
let r = this.peri.regs();
let drop = OnDrop::new(move || {
info!("read drop: stopping");
r.intenclr.write(|w| w.endrx().clear());
r.tasks_stoprx.write(|w| unsafe { w.bits(1) });
// TX is stopped almost instantly, spinning is fine.
while r.events_endrx.read().bits() == 0 {}
info!("read drop: stopped");
});
r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) });
r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) });
r.events_endrx.reset();
r.intenset.write(|w| w.endrx().set());
compiler_fence(Ordering::SeqCst);
trace!("startrx");
r.tasks_startrx.write(|w| unsafe { w.bits(1) });
let irq = &mut this.irq;
poll_fn(|cx| {
if r.events_endrx.read().bits() != 0 {
r.events_endrx.reset();
return Poll::Ready(());
}
wake_on_interrupt(irq, cx.waker());
Poll::Pending
})
.await;
compiler_fence(Ordering::SeqCst);
r.intenclr.write(|w| w.endrx().clear());
drop.defuse();
Ok(())
2021-01-02 19:59:37 +01:00
}
}
2021-03-22 01:15:44 +01:00
}
2021-01-02 19:59:37 +01:00
2021-03-22 01:15:44 +01:00
impl<'d, T: Instance> Write for Uarte<'d, T> {
#[rustfmt::skip]
type WriteFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a;
fn write<'a>(self: Pin<&'a mut Self>, tx_buffer: &'a [u8]) -> Self::WriteFuture<'a> {
async move {
let this = unsafe { self.get_unchecked_mut() };
let ptr = tx_buffer.as_ptr();
let len = tx_buffer.len();
assert!(len <= EASY_DMA_SIZE);
// TODO: panic if buffer is not in SRAM
let r = this.peri.regs();
let drop = OnDrop::new(move || {
info!("write drop: stopping");
r.intenclr.write(|w| w.endtx().clear());
r.tasks_stoptx.write(|w| unsafe { w.bits(1) });
// TX is stopped almost instantly, spinning is fine.
while r.events_endtx.read().bits() == 0 {}
info!("write drop: stopped");
});
r.txd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) });
r.txd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) });
r.events_endtx.reset();
r.intenset.write(|w| w.endtx().set());
compiler_fence(Ordering::SeqCst);
trace!("starttx");
r.tasks_starttx.write(|w| unsafe { w.bits(1) });
let irq = &mut this.irq;
poll_fn(|cx| {
if r.events_endtx.read().bits() != 0 {
r.events_endtx.reset();
return Poll::Ready(());
}
wake_on_interrupt(irq, cx.waker());
Poll::Pending
})
.await;
compiler_fence(Ordering::SeqCst);
r.intenclr.write(|w| w.endtx().clear());
drop.defuse();
Ok(())
2021-01-02 19:59:37 +01:00
}
}
}
2021-03-22 01:15:44 +01:00
/*
2020-12-23 16:18:29 +01:00
/// Future for the [`Uarte::send()`] method.
2021-01-02 19:14:54 +01:00
pub struct SendFuture<'a, T>
2020-12-23 16:18:29 +01:00
where
T: Instance,
{
uarte: &'a mut Uarte<T>,
2021-01-02 19:14:54 +01:00
buf: &'a [u8],
2020-12-23 16:18:29 +01:00
}
2021-01-02 19:14:54 +01:00
impl<'a, T> Drop for SendFuture<'a, T>
2020-12-23 16:18:29 +01:00
where
T: Instance,
{
fn drop(self: &mut Self) {
if self.uarte.tx_started() {
trace!("stoptx");
// Stop the transmitter to minimize the current consumption.
2021-03-22 01:15:44 +01:00
self.uarte.peri.events_txstarted.reset();
self.uarte.peri.tasks_stoptx.write(|w| unsafe { w.bits(1) });
2021-01-03 17:05:04 +01:00
// TX is stopped almost instantly, spinning is fine.
while !T::state().tx_done.signaled() {}
2020-12-23 16:18:29 +01:00
}
}
}
/// Future for the [`Uarte::receive()`] method.
2021-01-02 19:14:54 +01:00
pub struct ReceiveFuture<'a, T>
2020-12-23 16:18:29 +01:00
where
T: Instance,
{
uarte: &'a mut Uarte<T>,
2021-01-02 19:14:54 +01:00
buf: &'a mut [u8],
2020-12-23 16:18:29 +01:00
}
2021-01-02 19:14:54 +01:00
impl<'a, T> Drop for ReceiveFuture<'a, T>
2020-12-23 16:18:29 +01:00
where
T: Instance,
{
fn drop(self: &mut Self) {
if self.uarte.rx_started() {
trace!("stoprx (drop)");
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
self.uarte.peri.events_rxstarted.reset();
self.uarte.peri.tasks_stoprx.write(|w| unsafe { w.bits(1) });
2021-01-03 17:05:04 +01:00
2021-03-08 00:15:40 +01:00
embassy_extras::low_power_wait_until(|| T::state().rx_done.signaled())
2020-12-23 16:18:29 +01:00
}
}
}
2021-01-02 19:14:54 +01:00
impl<'a, T> Future for ReceiveFuture<'a, T>
2020-12-23 16:18:29 +01:00
where
T: Instance,
{
2021-03-02 00:32:23 +01:00
type Output = Result<(), embassy::traits::uart::Error>;
2020-12-23 16:18:29 +01:00
2021-01-02 19:14:54 +01:00
fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2020-12-23 16:18:29 +01:00
let Self { uarte, buf } = unsafe { self.get_unchecked_mut() };
match T::state().rx_done.poll_wait(cx) {
Poll::Pending if !uarte.rx_started() => {
let ptr = buf.as_ptr();
let len = buf.len();
assert!(len <= EASY_DMA_SIZE);
2021-01-03 17:05:04 +01:00
uarte.enable();
2020-12-23 16:18:29 +01:00
compiler_fence(Ordering::SeqCst);
2021-03-22 01:15:44 +01:00
r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) });
r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) });
2020-12-23 16:18:29 +01:00
trace!("startrx");
2021-03-22 01:15:44 +01:00
uarte.peri.tasks_startrx.write(|w| unsafe { w.bits(1) });
while !uarte.rx_started() {} // Make sure reception has started
Poll::Pending
}
Poll::Pending => Poll::Pending,
Poll::Ready(_) => Poll::Ready(Ok(())),
2020-12-23 16:18:29 +01:00
}
}
}
/// Future for the [`receive()`] method.
2021-01-02 19:14:54 +01:00
impl<'a, T> ReceiveFuture<'a, T>
2020-12-23 16:18:29 +01:00
where
T: Instance,
{
/// Stops the ongoing reception and returns the number of bytes received.
2021-01-02 19:14:54 +01:00
pub async fn stop(self) -> usize {
let len = if self.uarte.rx_started() {
trace!("stoprx (stop)");
2021-03-22 01:15:44 +01:00
self.uarte.peri.events_rxstarted.reset();
self.uarte.peri.tasks_stoprx.write(|w| unsafe { w.bits(1) });
T::state().rx_done.wait().await
} else {
// Transfer was stopped before it even started. No bytes were sent.
0
};
2021-01-02 19:14:54 +01:00
len as _
2020-12-23 16:18:29 +01:00
}
}
2021-03-22 01:15:44 +01:00
*/
mod sealed {
use super::*;
2020-12-23 16:18:29 +01:00
2021-03-22 01:15:44 +01:00
pub trait Instance {
fn regs(&self) -> &pac::uarte0::RegisterBlock;
}
2020-12-23 16:18:29 +01:00
}
2021-03-22 01:15:44 +01:00
pub trait Instance: sealed::Instance + 'static {
type Interrupt: Interrupt;
2020-12-23 16:18:29 +01:00
}
2021-03-22 01:15:44 +01:00
macro_rules! make_impl {
($type:ident, $irq:ident) => {
impl sealed::Instance for peripherals::$type {
fn regs(&self) -> &pac::uarte0::RegisterBlock {
unsafe { &*pac::$type::ptr() }
}
}
impl Instance for peripherals::$type {
type Interrupt = interrupt::$irq;
}
};
2020-12-23 16:18:29 +01:00
}
2021-03-22 01:15:44 +01:00
make_impl!(UARTE0, UARTE0_UART0);
2020-12-23 16:18:29 +01:00
#[cfg(any(feature = "52833", feature = "52840", feature = "9160"))]
2021-03-22 01:15:44 +01:00
make_impl!(UARTE1, UARTE1);