Remove pin from Uart

This commit is contained in:
Dario Nieuwenhuis 2021-04-14 16:01:43 +02:00
parent b34b74de9d
commit 59ccc45f28
5 changed files with 72 additions and 87 deletions

View File

@ -15,7 +15,6 @@ use embassy::traits::uart::{Read, Write};
use embassy::util::Steal; use embassy::util::Steal;
use embassy_nrf::gpio::NoPin; use embassy_nrf::gpio::NoPin;
use embassy_nrf::{interrupt, uarte, Peripherals}; use embassy_nrf::{interrupt, uarte, Peripherals};
use futures::pin_mut;
#[embassy::main] #[embassy::main]
async fn main(spawner: Spawner) { async fn main(spawner: Spawner) {
@ -26,8 +25,8 @@ async fn main(spawner: Spawner) {
config.baudrate = uarte::Baudrate::BAUD115200; config.baudrate = uarte::Baudrate::BAUD115200;
let irq = interrupt::take!(UARTE0_UART0); let irq = interrupt::take!(UARTE0_UART0);
let uart = unsafe { uarte::Uarte::new(p.UARTE0, irq, p.P0_08, p.P0_06, NoPin, NoPin, config) }; let mut uart =
pin_mut!(uart); unsafe { uarte::Uarte::new(p.UARTE0, irq, p.P0_08, p.P0_06, NoPin, NoPin, config) };
info!("uarte initialized!"); info!("uarte initialized!");
@ -35,14 +34,14 @@ async fn main(spawner: Spawner) {
let mut buf = [0; 8]; let mut buf = [0; 8];
buf.copy_from_slice(b"Hello!\r\n"); buf.copy_from_slice(b"Hello!\r\n");
unwrap!(uart.as_mut().write(&buf).await); unwrap!(uart.write(&buf).await);
info!("wrote hello in uart!"); info!("wrote hello in uart!");
loop { loop {
info!("reading..."); info!("reading...");
unwrap!(uart.as_mut().read(&mut buf).await); unwrap!(uart.read(&mut buf).await);
info!("writing..."); info!("writing...");
unwrap!(uart.as_mut().write(&buf).await); unwrap!(uart.write(&buf).await);
/* /*
// `receive()` doesn't return until the buffer has been completely filled with // `receive()` doesn't return until the buffer has been completely filled with

View File

@ -78,7 +78,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> {
) -> Self { ) -> Self {
unborrow!(uarte, timer, ppi_ch1, ppi_ch2, irq, rxd, txd, cts, rts); unborrow!(uarte, timer, ppi_ch1, ppi_ch2, irq, rxd, txd, cts, rts);
let r = uarte.regs(); let r = U::regs();
let rt = timer.regs(); let rt = timer.regs();
rxd.conf().write(|w| w.input().connect().drive().h0h1()); rxd.conf().write(|w| w.input().connect().drive().h0h1());
@ -178,7 +178,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> BufferedUarte<'d, U, T> {
pub fn set_baudrate(self: Pin<&mut Self>, baudrate: Baudrate) { pub fn set_baudrate(self: Pin<&mut Self>, baudrate: Baudrate) {
self.inner().with(|state, _irq| { self.inner().with(|state, _irq| {
let r = state.uarte.regs(); let r = U::regs();
let rt = state.timer.regs(); let rt = state.timer.regs();
let timeout = 0x8000_0000 / (baudrate as u32 / 40); let timeout = 0x8000_0000 / (baudrate as u32 / 40);
@ -265,7 +265,7 @@ impl<'d, U: UarteInstance, T: TimerInstance> AsyncWrite for BufferedUarte<'d, U,
impl<'a, U: UarteInstance, T: TimerInstance> Drop for State<'a, U, T> { impl<'a, U: UarteInstance, T: TimerInstance> Drop for State<'a, U, T> {
fn drop(&mut self) { fn drop(&mut self) {
let r = self.uarte.regs(); let r = U::regs();
let rt = self.timer.regs(); let rt = self.timer.regs();
// TODO this probably deadlocks. do like Uarte instead. // TODO this probably deadlocks. do like Uarte instead.
@ -290,7 +290,7 @@ impl<'a, U: UarteInstance, T: TimerInstance> PeripheralState for State<'a, U, T>
type Interrupt = U::Interrupt; type Interrupt = U::Interrupt;
fn on_interrupt(&mut self) { fn on_interrupt(&mut self) {
trace!("irq: start"); trace!("irq: start");
let r = self.uarte.regs(); let r = U::regs();
let rt = self.timer.regs(); let rt = self.timer.regs();
loop { loop {

View File

@ -2,12 +2,11 @@
use core::future::Future; use core::future::Future;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::pin::Pin; use core::sync::atomic::{compiler_fence, Ordering};
use core::sync::atomic::{compiler_fence, AtomicBool, Ordering};
use core::task::Poll; use core::task::Poll;
use embassy::interrupt::InterruptExt;
use embassy::traits::uart::{Error, Read, Write}; use embassy::traits::uart::{Error, Read, Write};
use embassy::util::{AtomicWaker, OnDrop, PeripheralBorrow}; use embassy::util::{AtomicWaker, OnDrop, PeripheralBorrow};
use embassy_extras::peripheral_shared::{Peripheral, PeripheralState};
use embassy_extras::unborrow; use embassy_extras::unborrow;
use futures::future::poll_fn; use futures::future::poll_fn;
@ -38,16 +37,9 @@ impl Default for Config {
} }
} }
struct State<T: Instance> {
peri: T,
endrx_waker: AtomicWaker,
endtx_waker: AtomicWaker,
}
/// Interface to the UARTE peripheral /// Interface to the UARTE peripheral
pub struct Uarte<'d, T: Instance> { pub struct Uarte<'d, T: Instance> {
inner: Peripheral<State<T>>, peri: T,
phantom: PhantomData<&'d mut T>, phantom: PhantomData<&'d mut T>,
} }
@ -72,7 +64,7 @@ impl<'d, T: Instance> Uarte<'d, T> {
) -> Self { ) -> Self {
unborrow!(uarte, irq, rxd, txd, cts, rts); unborrow!(uarte, irq, rxd, txd, cts, rts);
let r = uarte.regs(); let r = T::regs();
assert!(r.enable.read().enable().is_disabled()); assert!(r.enable.read().enable().is_disabled());
@ -115,38 +107,29 @@ impl<'d, T: Instance> Uarte<'d, T> {
r.events_rxstarted.reset(); r.events_rxstarted.reset();
r.events_txstarted.reset(); r.events_txstarted.reset();
irq.set_handler(Self::on_interrupt);
irq.unpend();
irq.enable();
// Enable // Enable
r.enable.write(|w| w.enable().enabled()); r.enable.write(|w| w.enable().enabled());
Self { Self {
inner: Peripheral::new( peri: uarte,
irq,
State {
peri: uarte,
endrx_waker: AtomicWaker::new(),
endtx_waker: AtomicWaker::new(),
},
),
phantom: PhantomData, phantom: PhantomData,
} }
} }
fn inner(self: Pin<&mut Self>) -> Pin<&mut Peripheral<State<T>>> { fn on_interrupt(_: *mut ()) {
unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) } let r = T::regs();
} let s = T::state();
}
impl<T: Instance> PeripheralState for State<T> {
type Interrupt = T::Interrupt;
fn on_interrupt(&self) {
let r = self.peri.regs();
if r.events_endrx.read().bits() != 0 { if r.events_endrx.read().bits() != 0 {
self.endrx_waker.wake(); s.endrx_waker.wake();
r.intenclr.write(|w| w.endrx().clear()); r.intenclr.write(|w| w.endrx().clear());
} }
if r.events_endtx.read().bits() != 0 { if r.events_endtx.read().bits() != 0 {
self.endtx_waker.wake(); s.endtx_waker.wake();
r.intenclr.write(|w| w.endtx().clear()); r.intenclr.write(|w| w.endtx().clear());
} }
@ -163,8 +146,7 @@ impl<'a, T: Instance> Drop for Uarte<'a, T> {
fn drop(&mut self) { fn drop(&mut self) {
info!("uarte drop"); info!("uarte drop");
let s = unsafe { Pin::new_unchecked(&mut self.inner) }.state(); let r = T::regs();
let r = s.peri.regs();
let did_stoprx = r.events_rxstarted.read().bits() != 0; let did_stoprx = r.events_rxstarted.read().bits() != 0;
let did_stoptx = r.events_txstarted.read().bits() != 0; let did_stoptx = r.events_txstarted.read().bits() != 0;
@ -194,16 +176,14 @@ impl<'d, T: Instance> Read for Uarte<'d, T> {
#[rustfmt::skip] #[rustfmt::skip]
type ReadFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a; type ReadFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a;
fn read<'a>(mut self: Pin<&'a mut Self>, rx_buffer: &'a mut [u8]) -> Self::ReadFuture<'a> { fn read<'a>(&'a mut self, rx_buffer: &'a mut [u8]) -> Self::ReadFuture<'a> {
self.as_mut().inner().register_interrupt();
async move { async move {
let ptr = rx_buffer.as_ptr(); let ptr = rx_buffer.as_ptr();
let len = rx_buffer.len(); let len = rx_buffer.len();
assert!(len <= EASY_DMA_SIZE); assert!(len <= EASY_DMA_SIZE);
let s = self.inner().state(); let r = T::regs();
let r = s.peri.regs(); let s = T::state();
let drop = OnDrop::new(move || { let drop = OnDrop::new(move || {
info!("read drop: stopping"); info!("read drop: stopping");
@ -250,17 +230,15 @@ impl<'d, T: Instance> Write for Uarte<'d, T> {
#[rustfmt::skip] #[rustfmt::skip]
type WriteFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a; type WriteFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a;
fn write<'a>(mut self: Pin<&'a mut Self>, tx_buffer: &'a [u8]) -> Self::WriteFuture<'a> { fn write<'a>(&'a mut self, tx_buffer: &'a [u8]) -> Self::WriteFuture<'a> {
self.as_mut().inner().register_interrupt();
async move { async move {
let ptr = tx_buffer.as_ptr(); let ptr = tx_buffer.as_ptr();
let len = tx_buffer.len(); let len = tx_buffer.len();
assert!(len <= EASY_DMA_SIZE); assert!(len <= EASY_DMA_SIZE);
// TODO: panic if buffer is not in SRAM // TODO: panic if buffer is not in SRAM
let s = self.inner().state(); let r = T::regs();
let r = s.peri.regs(); let s = T::state();
let drop = OnDrop::new(move || { let drop = OnDrop::new(move || {
info!("write drop: stopping"); info!("write drop: stopping");
@ -306,8 +284,22 @@ impl<'d, T: Instance> Write for Uarte<'d, T> {
mod sealed { mod sealed {
use super::*; use super::*;
pub struct State {
pub endrx_waker: AtomicWaker,
pub endtx_waker: AtomicWaker,
}
impl State {
pub const fn new() -> Self {
Self {
endrx_waker: AtomicWaker::new(),
endtx_waker: AtomicWaker::new(),
}
}
}
pub trait Instance { pub trait Instance {
fn regs(&self) -> &pac::uarte0::RegisterBlock; fn regs() -> &'static pac::uarte0::RegisterBlock;
fn state() -> &'static State;
} }
} }
@ -318,9 +310,13 @@ pub trait Instance: sealed::Instance + 'static {
macro_rules! impl_instance { macro_rules! impl_instance {
($type:ident, $irq:ident) => { ($type:ident, $irq:ident) => {
impl sealed::Instance for peripherals::$type { impl sealed::Instance for peripherals::$type {
fn regs(&self) -> &pac::uarte0::RegisterBlock { fn regs() -> &'static pac::uarte0::RegisterBlock {
unsafe { &*pac::$type::ptr() } unsafe { &*pac::$type::ptr() }
} }
fn state() -> &'static sealed::State {
static STATE: sealed::State = sealed::State::new();
&STATE
}
} }
impl Instance for peripherals::$type { impl Instance for peripherals::$type {
type Interrupt = interrupt::$irq; type Interrupt = interrupt::$irq;

View File

@ -2,7 +2,6 @@
use core::future::Future; use core::future::Future;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::pin::Pin;
use embassy::interrupt::Interrupt; use embassy::interrupt::Interrupt;
use embassy::traits::uart::{Error, Read, ReadUntilIdle, Write}; use embassy::traits::uart::{Error, Read, ReadUntilIdle, Write};
use embassy::util::InterruptFuture; use embassy::util::InterruptFuture;
@ -101,13 +100,12 @@ where
/// Receives serial data. /// Receives serial data.
/// ///
/// The future is pending until the buffer is completely filled. /// The future is pending until the buffer is completely filled.
fn read<'a>(self: Pin<&'a mut Self>, buf: &'a mut [u8]) -> Self::ReadFuture<'a> { fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::ReadFuture<'a> {
let this = unsafe { self.get_unchecked_mut() };
let static_buf = unsafe { core::mem::transmute::<&'a mut [u8], &'static mut [u8]>(buf) }; let static_buf = unsafe { core::mem::transmute::<&'a mut [u8], &'static mut [u8]>(buf) };
async move { async move {
let rx_stream = this.rx_stream.take().unwrap(); let rx_stream = self.rx_stream.take().unwrap();
let usart = this.usart.take().unwrap(); let usart = self.usart.take().unwrap();
let mut rx_transfer = Transfer::init( let mut rx_transfer = Transfer::init(
rx_stream, rx_stream,
@ -120,13 +118,13 @@ where
.double_buffer(false), .double_buffer(false),
); );
let fut = InterruptFuture::new(&mut this.rx_int); let fut = InterruptFuture::new(&mut self.rx_int);
rx_transfer.start(|_usart| {}); rx_transfer.start(|_usart| {});
fut.await; fut.await;
let (rx_stream, usart, _, _) = rx_transfer.free(); let (rx_stream, usart, _, _) = rx_transfer.free();
this.rx_stream.replace(rx_stream); self.rx_stream.replace(rx_stream);
this.usart.replace(usart); self.usart.replace(usart);
Ok(()) Ok(())
} }
@ -148,14 +146,13 @@ where
type WriteFuture<'a> = impl Future<Output = Result<(), Error>> + 'a; type WriteFuture<'a> = impl Future<Output = Result<(), Error>> + 'a;
/// Sends serial data. /// Sends serial data.
fn write<'a>(self: Pin<&'a mut Self>, buf: &'a [u8]) -> Self::WriteFuture<'a> { fn write<'a>(&'a mut self, buf: &'a [u8]) -> Self::WriteFuture<'a> {
let this = unsafe { self.get_unchecked_mut() };
#[allow(mutable_transmutes)] #[allow(mutable_transmutes)]
let static_buf = unsafe { core::mem::transmute::<&'a [u8], &'static mut [u8]>(buf) }; let static_buf = unsafe { core::mem::transmute::<&'a [u8], &'static mut [u8]>(buf) };
async move { async move {
let tx_stream = this.tx_stream.take().unwrap(); let tx_stream = self.tx_stream.take().unwrap();
let usart = this.usart.take().unwrap(); let usart = self.usart.take().unwrap();
let mut tx_transfer = Transfer::init( let mut tx_transfer = Transfer::init(
tx_stream, tx_stream,
@ -168,15 +165,15 @@ where
.double_buffer(false), .double_buffer(false),
); );
let fut = InterruptFuture::new(&mut this.tx_int); let fut = InterruptFuture::new(&mut self.tx_int);
tx_transfer.start(|_usart| {}); tx_transfer.start(|_usart| {});
fut.await; fut.await;
let (tx_stream, usart, _buf, _) = tx_transfer.free(); let (tx_stream, usart, _buf, _) = tx_transfer.free();
this.tx_stream.replace(tx_stream); self.tx_stream.replace(tx_stream);
this.usart.replace(usart); self.usart.replace(usart);
Ok(()) Ok(())
} }
@ -202,16 +199,12 @@ where
/// The future is pending until either the buffer is completely full, or the RX line falls idle after receiving some data. /// The future is pending until either the buffer is completely full, or the RX line falls idle after receiving some data.
/// ///
/// Returns the number of bytes read. /// Returns the number of bytes read.
fn read_until_idle<'a>( fn read_until_idle<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::ReadUntilIdleFuture<'a> {
self: Pin<&'a mut Self>,
buf: &'a mut [u8],
) -> Self::ReadUntilIdleFuture<'a> {
let this = unsafe { self.get_unchecked_mut() };
let static_buf = unsafe { core::mem::transmute::<&'a mut [u8], &'static mut [u8]>(buf) }; let static_buf = unsafe { core::mem::transmute::<&'a mut [u8], &'static mut [u8]>(buf) };
async move { async move {
let rx_stream = this.rx_stream.take().unwrap(); let rx_stream = self.rx_stream.take().unwrap();
let usart = this.usart.take().unwrap(); let usart = self.usart.take().unwrap();
unsafe { unsafe {
/* __HAL_UART_ENABLE_IT(&uart->UartHandle, UART_IT_IDLE); */ /* __HAL_UART_ENABLE_IT(&uart->UartHandle, UART_IT_IDLE); */
@ -235,8 +228,8 @@ where
let total_bytes = RSTREAM::get_number_of_transfers() as usize; let total_bytes = RSTREAM::get_number_of_transfers() as usize;
let fut = InterruptFuture::new(&mut this.rx_int); let fut = InterruptFuture::new(&mut self.rx_int);
let fut_idle = InterruptFuture::new(&mut this.usart_int); let fut_idle = InterruptFuture::new(&mut self.usart_int);
rx_transfer.start(|_usart| {}); rx_transfer.start(|_usart| {});
@ -249,8 +242,8 @@ where
unsafe { unsafe {
(*USART::ptr()).cr1.modify(|_, w| w.idleie().clear_bit()); (*USART::ptr()).cr1.modify(|_, w| w.idleie().clear_bit());
} }
this.rx_stream.replace(rx_stream); self.rx_stream.replace(rx_stream);
this.usart.replace(usart); self.usart.replace(usart);
Ok(total_bytes - remaining_bytes) Ok(total_bytes - remaining_bytes)
} }

View File

@ -13,7 +13,7 @@ pub trait Read {
where where
Self: 'a; Self: 'a;
fn read<'a>(self: Pin<&'a mut Self>, buf: &'a mut [u8]) -> Self::ReadFuture<'a>; fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::ReadFuture<'a>;
} }
pub trait ReadUntilIdle { pub trait ReadUntilIdle {
@ -23,10 +23,7 @@ pub trait ReadUntilIdle {
/// Receive into the buffer until the buffer is full or the line is idle after some bytes are received /// Receive into the buffer until the buffer is full or the line is idle after some bytes are received
/// Return the number of bytes received /// Return the number of bytes received
fn read_until_idle<'a>( fn read_until_idle<'a>(&'a mut self, buf: &'a mut [u8]) -> Self::ReadUntilIdleFuture<'a>;
self: Pin<&'a mut Self>,
buf: &'a mut [u8],
) -> Self::ReadUntilIdleFuture<'a>;
} }
pub trait Write { pub trait Write {
@ -34,5 +31,5 @@ pub trait Write {
where where
Self: 'a; Self: 'a;
fn write<'a>(self: Pin<&'a mut Self>, buf: &'a [u8]) -> Self::WriteFuture<'a>; fn write<'a>(&'a mut self, buf: &'a [u8]) -> Self::WriteFuture<'a>;
} }