nrf/uarte: expose all functionality as inherent methods.

This commit is contained in:
Dario Nieuwenhuis 2022-01-13 22:24:13 +01:00
parent c432d036c7
commit 3e503e7335
4 changed files with 292 additions and 225 deletions

View File

@ -13,12 +13,10 @@
//! memory may be used given that buffers are passed in directly to its read and write //! memory may be used given that buffers are passed in directly to its read and write
//! methods. //! methods.
use core::future::Future;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::sync::atomic::{compiler_fence, Ordering}; use core::sync::atomic::{compiler_fence, Ordering};
use core::task::Poll; use core::task::Poll;
use embassy::interrupt::InterruptExt; use embassy::interrupt::InterruptExt;
use embassy::traits::uart::{Error as TraitError, Read, ReadUntilIdle, Write};
use embassy::util::Unborrow; use embassy::util::Unborrow;
use embassy_hal_common::drop::OnDrop; use embassy_hal_common::drop::OnDrop;
use embassy_hal_common::unborrow; use embassy_hal_common::unborrow;
@ -32,6 +30,7 @@ use crate::pac;
use crate::ppi::{AnyConfigurableChannel, ConfigurableChannel, Event, Ppi, Task}; use crate::ppi::{AnyConfigurableChannel, ConfigurableChannel, Event, Ppi, Task};
use crate::timer::Instance as TimerInstance; use crate::timer::Instance as TimerInstance;
use crate::timer::{Frequency, Timer}; use crate::timer::{Frequency, Timer};
use crate::util::slice_in_ram_or;
// Re-export SVD variants to allow user to directly set values. // 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}; pub use pac::uarte0::{baudrate::BAUDRATE_A as Baudrate, config::PARITY_A as Parity};
@ -51,6 +50,16 @@ impl Default for Config {
} }
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Error {
BufferTooLong,
BufferZeroLength,
DMABufferNotInDataMemory,
// TODO: add other error variants.
}
/// Interface to the UARTE peripheral /// Interface to the UARTE peripheral
pub struct Uarte<'d, T: Instance> { pub struct Uarte<'d, T: Instance> {
phantom: PhantomData<&'d mut T>, phantom: PhantomData<&'d mut T>,
@ -139,8 +148,12 @@ impl<'d, T: Instance> Uarte<'d, T> {
Self { Self {
phantom: PhantomData, phantom: PhantomData,
tx: UarteTx::new(), tx: UarteTx {
rx: UarteRx::new(), phantom: PhantomData,
},
rx: UarteRx {
phantom: PhantomData,
},
} }
} }
@ -170,50 +183,36 @@ impl<'d, T: Instance> Uarte<'d, T> {
r.intenclr.write(|w| w.endtx().clear()); r.intenclr.write(|w| w.endtx().clear());
} }
} }
}
impl<'d, T: Instance> Read for Uarte<'d, T> { pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
type ReadFuture<'a> self.rx.read(buffer).await
where
Self: 'a,
= impl Future<Output = Result<(), TraitError>> + 'a;
fn read<'a>(&'a mut self, rx_buffer: &'a mut [u8]) -> Self::ReadFuture<'a> {
self.rx.read(rx_buffer)
} }
}
impl<'d, T: Instance> Write for Uarte<'d, T> { pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
type WriteFuture<'a> self.tx.write(buffer).await
where }
Self: 'a,
= impl Future<Output = Result<(), TraitError>> + 'a;
fn write<'a>(&'a mut self, tx_buffer: &'a [u8]) -> Self::WriteFuture<'a> { pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
self.tx.write(tx_buffer) self.rx.blocking_read(buffer)
}
pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
self.tx.blocking_write(buffer)
} }
} }
impl<'d, T: Instance> UarteTx<'d, T> { impl<'d, T: Instance> UarteTx<'d, T> {
pub fn new() -> Self { pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
Self { slice_in_ram_or(buffer, Error::DMABufferNotInDataMemory)?;
phantom: PhantomData, if buffer.len() == 0 {
return Err(Error::BufferZeroLength);
} }
if buffer.len() > EASY_DMA_SIZE {
return Err(Error::BufferTooLong);
} }
}
impl<'d, T: Instance> Write for UarteTx<'d, T> { let ptr = buffer.as_ptr();
type WriteFuture<'a> let len = buffer.len();
where
Self: 'a,
= impl Future<Output = Result<(), TraitError>> + 'a;
fn write<'a>(&'a mut self, tx_buffer: &'a [u8]) -> Self::WriteFuture<'a> {
async move {
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 = T::regs(); let r = T::regs();
let s = T::state(); let s = T::state();
@ -256,6 +255,38 @@ impl<'d, T: Instance> Write for UarteTx<'d, T> {
Ok(()) Ok(())
} }
pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
slice_in_ram_or(buffer, Error::DMABufferNotInDataMemory)?;
if buffer.len() == 0 {
return Err(Error::BufferZeroLength);
}
if buffer.len() > EASY_DMA_SIZE {
return Err(Error::BufferTooLong);
}
let ptr = buffer.as_ptr();
let len = buffer.len();
let r = T::regs();
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.intenclr.write(|w| w.endtx().clear());
compiler_fence(Ordering::SeqCst);
trace!("starttx");
r.tasks_starttx.write(|w| unsafe { w.bits(1) });
while r.events_endtx.read().bits() == 0 {}
compiler_fence(Ordering::SeqCst);
r.events_txstarted.reset();
Ok(())
} }
} }
@ -278,24 +309,16 @@ impl<'a, T: Instance> Drop for UarteTx<'a, T> {
} }
impl<'d, T: Instance> UarteRx<'d, T> { impl<'d, T: Instance> UarteRx<'d, T> {
pub fn new() -> Self { pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
Self { if buffer.len() == 0 {
phantom: PhantomData, return Err(Error::BufferZeroLength);
} }
if buffer.len() > EASY_DMA_SIZE {
return Err(Error::BufferTooLong);
} }
}
impl<'d, T: Instance> Read for UarteRx<'d, T> { let ptr = buffer.as_ptr();
type ReadFuture<'a> let len = buffer.len();
where
Self: 'a,
= impl Future<Output = Result<(), TraitError>> + 'a;
fn read<'a>(&'a mut self, rx_buffer: &'a mut [u8]) -> Self::ReadFuture<'a> {
async move {
let ptr = rx_buffer.as_ptr();
let len = rx_buffer.len();
assert!(len <= EASY_DMA_SIZE);
let r = T::regs(); let r = T::regs();
let s = T::state(); let s = T::state();
@ -338,6 +361,37 @@ impl<'d, T: Instance> Read for UarteRx<'d, T> {
Ok(()) Ok(())
} }
pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
if buffer.len() == 0 {
return Err(Error::BufferZeroLength);
}
if buffer.len() > EASY_DMA_SIZE {
return Err(Error::BufferTooLong);
}
let ptr = buffer.as_ptr();
let len = buffer.len();
let r = T::regs();
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.intenclr.write(|w| w.endrx().clear());
compiler_fence(Ordering::SeqCst);
trace!("startrx");
r.tasks_startrx.write(|w| unsafe { w.bits(1) });
while r.events_endrx.read().bits() == 0 {}
compiler_fence(Ordering::SeqCst);
r.events_rxstarted.reset();
Ok(())
} }
} }
@ -439,14 +493,7 @@ pub struct UarteWithIdle<'d, U: Instance, T: TimerInstance> {
impl<'d, U: Instance, T: TimerInstance> UarteWithIdle<'d, U, T> { impl<'d, U: Instance, T: TimerInstance> UarteWithIdle<'d, U, T> {
/// Creates the interface to a UARTE instance. /// Creates the interface to a UARTE instance.
/// Sets the baud rate, parity and assigns the pins to the UARTE peripheral. /// Sets the baud rate, parity and assigns the pins to the UARTE peripheral.
/// pub fn new(
/// # Safety
///
/// 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(
uarte: impl Unborrow<Target = U> + 'd, uarte: impl Unborrow<Target = U> + 'd,
timer: impl Unborrow<Target = T> + 'd, timer: impl Unborrow<Target = T> + 'd,
ppi_ch1: impl Unborrow<Target = impl ConfigurableChannel + 'd> + 'd, ppi_ch1: impl Unborrow<Target = impl ConfigurableChannel + 'd> + 'd,
@ -501,22 +548,41 @@ impl<'d, U: Instance, T: TimerInstance> UarteWithIdle<'d, U, T> {
_ppi_ch2: ppi_ch2, _ppi_ch2: ppi_ch2,
} }
} }
}
impl<'d, U: Instance, T: TimerInstance> ReadUntilIdle for UarteWithIdle<'d, U, T> { pub async fn read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
type ReadUntilIdleFuture<'a> self.ppi_ch1.disable();
where self.uarte.read(buffer).await
Self: 'a, }
= impl Future<Output = Result<usize, TraitError>> + 'a;
fn read_until_idle<'a>(&'a mut self, rx_buffer: &'a mut [u8]) -> Self::ReadUntilIdleFuture<'a> { pub async fn write(&mut self, buffer: &[u8]) -> Result<(), Error> {
async move { self.uarte.write(buffer).await
let ptr = rx_buffer.as_ptr(); }
let len = rx_buffer.len();
assert!(len <= EASY_DMA_SIZE); pub fn blocking_read(&mut self, buffer: &mut [u8]) -> Result<(), Error> {
self.ppi_ch1.disable();
self.uarte.blocking_read(buffer)
}
pub fn blocking_write(&mut self, buffer: &[u8]) -> Result<(), Error> {
self.uarte.blocking_write(buffer)
}
pub async fn read_until_idle(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
if buffer.len() == 0 {
return Err(Error::BufferZeroLength);
}
if buffer.len() > EASY_DMA_SIZE {
return Err(Error::BufferTooLong);
}
let ptr = buffer.as_ptr();
let len = buffer.len();
let r = U::regs(); let r = U::regs();
let s = U::state(); let s = U::state();
self.ppi_ch1.enable();
let drop = OnDrop::new(|| { let drop = OnDrop::new(|| {
trace!("read drop: stopping"); trace!("read drop: stopping");
@ -539,7 +605,6 @@ impl<'d, U: Instance, T: TimerInstance> ReadUntilIdle for UarteWithIdle<'d, U, T
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
trace!("startrx");
r.tasks_startrx.write(|w| unsafe { w.bits(1) }); r.tasks_startrx.write(|w| unsafe { w.bits(1) });
poll_fn(|cx| { poll_fn(|cx| {
@ -554,7 +619,6 @@ impl<'d, U: Instance, T: TimerInstance> ReadUntilIdle for UarteWithIdle<'d, U, T
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
let n = r.rxd.amount.read().amount().bits() as usize; let n = r.rxd.amount.read().amount().bits() as usize;
// Stop timer
self.timer.stop(); self.timer.stop();
r.events_rxstarted.reset(); r.events_rxstarted.reset();
@ -562,32 +626,41 @@ impl<'d, U: Instance, T: TimerInstance> ReadUntilIdle for UarteWithIdle<'d, U, T
Ok(n) Ok(n)
} }
}
}
impl<'d, U: Instance, T: TimerInstance> Read for UarteWithIdle<'d, U, T> { pub fn blocking_read_until_idle(&mut self, buffer: &mut [u8]) -> Result<usize, Error> {
type ReadFuture<'a> if buffer.len() == 0 {
where return Err(Error::BufferZeroLength);
Self: 'a, }
= impl Future<Output = Result<(), TraitError>> + 'a; if buffer.len() > EASY_DMA_SIZE {
fn read<'a>(&'a mut self, rx_buffer: &'a mut [u8]) -> Self::ReadFuture<'a> { return Err(Error::BufferTooLong);
async move { }
self.ppi_ch1.disable();
let result = self.uarte.read(rx_buffer).await; let ptr = buffer.as_ptr();
let len = buffer.len();
let r = U::regs();
self.ppi_ch1.enable(); self.ppi_ch1.enable();
result
}
}
}
impl<'d, U: Instance, T: TimerInstance> Write for UarteWithIdle<'d, U, T> { r.rxd.ptr.write(|w| unsafe { w.ptr().bits(ptr as u32) });
type WriteFuture<'a> r.rxd.maxcnt.write(|w| unsafe { w.maxcnt().bits(len as _) });
where
Self: 'a,
= impl Future<Output = Result<(), TraitError>> + 'a;
fn write<'a>(&'a mut self, tx_buffer: &'a [u8]) -> Self::WriteFuture<'a> { r.events_endrx.reset();
self.uarte.write(tx_buffer) r.intenclr.write(|w| w.endrx().clear());
compiler_fence(Ordering::SeqCst);
r.tasks_startrx.write(|w| unsafe { w.bits(1) });
while r.events_endrx.read().bits() == 0 {}
compiler_fence(Ordering::SeqCst);
let n = r.rxd.amount.read().amount().bits() as usize;
self.timer.stop();
r.events_rxstarted.reset();
Ok(n)
} }
} }

View File

@ -7,7 +7,6 @@ mod example_common;
use example_common::*; use example_common::*;
use embassy::executor::Spawner; use embassy::executor::Spawner;
use embassy::traits::uart::{Read, Write};
use embassy_nrf::gpio::NoPin; use embassy_nrf::gpio::NoPin;
use embassy_nrf::{interrupt, uarte, Peripherals}; use embassy_nrf::{interrupt, uarte, Peripherals};

View File

@ -4,11 +4,9 @@
#[path = "../example_common.rs"] #[path = "../example_common.rs"]
mod example_common; mod example_common;
use embassy_traits::uart::ReadUntilIdle;
use example_common::*; use example_common::*;
use embassy::executor::Spawner; use embassy::executor::Spawner;
use embassy::traits::uart::Write;
use embassy_nrf::gpio::NoPin; use embassy_nrf::gpio::NoPin;
use embassy_nrf::{interrupt, uarte, Peripherals}; use embassy_nrf::{interrupt, uarte, Peripherals};
@ -19,11 +17,9 @@ async fn main(_spawner: Spawner, p: Peripherals) {
config.baudrate = uarte::Baudrate::BAUD115200; config.baudrate = uarte::Baudrate::BAUD115200;
let irq = interrupt::take!(UARTE0_UART0); let irq = interrupt::take!(UARTE0_UART0);
let mut uart = unsafe { let mut uart = uarte::UarteWithIdle::new(
uarte::UarteWithIdle::new(
p.UARTE0, p.TIMER0, p.PPI_CH0, p.PPI_CH1, irq, p.P0_08, p.P0_06, NoPin, NoPin, config, p.UARTE0, p.TIMER0, p.PPI_CH0, p.PPI_CH1, irq, p.P0_08, p.P0_06, NoPin, NoPin, config,
) );
};
info!("uarte initialized!"); info!("uarte initialized!");

View File

@ -4,16 +4,15 @@
#[path = "../example_common.rs"] #[path = "../example_common.rs"]
mod example_common; mod example_common;
use embassy::blocking_mutex::kind::Noop;
use embassy::channel::mpsc::{self, Channel, Sender};
use embassy::util::Forever;
use embassy_nrf::peripherals::UARTE0;
use embassy_nrf::uarte::UarteRx;
use example_common::*; use example_common::*;
use embassy::blocking_mutex::kind::Noop;
use embassy::channel::mpsc::{self, Channel, Sender};
use embassy::executor::Spawner; use embassy::executor::Spawner;
use embassy::traits::uart::{Read, Write}; use embassy::util::Forever;
use embassy_nrf::gpio::NoPin; use embassy_nrf::gpio::NoPin;
use embassy_nrf::peripherals::UARTE0;
use embassy_nrf::uarte::UarteRx;
use embassy_nrf::{interrupt, uarte, Peripherals}; use embassy_nrf::{interrupt, uarte, Peripherals};
static CHANNEL: Forever<Channel<Noop, [u8; 8], 1>> = Forever::new(); static CHANNEL: Forever<Channel<Noop, [u8; 8], 1>> = Forever::new();