Merge pull request #141 from embassy-rs/no-pin

Remove Pin
This commit is contained in:
Dario Nieuwenhuis 2021-04-14 18:18:00 +02:00 committed by GitHub
commit bac53e3e55
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 248 additions and 258 deletions

View File

@ -21,9 +21,9 @@ use example_common::*;
#[embassy::task(pool_size = 4)] #[embassy::task(pool_size = 4)]
async fn button_task(n: usize, mut pin: PortInput<'static, AnyPin>) { async fn button_task(n: usize, mut pin: PortInput<'static, AnyPin>) {
loop { loop {
Pin::new(&mut pin).wait_for_low().await; pin.wait_for_low().await;
info!("Button {:?} pressed!", n); info!("Button {:?} pressed!", n);
Pin::new(&mut pin).wait_for_high().await; pin.wait_for_high().await;
info!("Button {:?} released!", n); info!("Button {:?} released!", n);
} }
} }

View File

@ -14,7 +14,6 @@ use embassy::traits::flash::Flash;
use embassy_nrf::Peripherals; use embassy_nrf::Peripherals;
use embassy_nrf::{interrupt, qspi}; use embassy_nrf::{interrupt, qspi};
use example_common::*; use example_common::*;
use futures::pin_mut;
const PAGE_SIZE: usize = 4096; const PAGE_SIZE: usize = 4096;
@ -36,32 +35,22 @@ async fn main(spawner: Spawner) {
let config = qspi::Config::default(); let config = qspi::Config::default();
let irq = interrupt::take!(QSPI); let irq = interrupt::take!(QSPI);
let q = qspi::Qspi::new(p.QSPI, irq, sck, csn, io0, io1, io2, io3, config); let mut q = qspi::Qspi::new(p.QSPI, irq, sck, csn, io0, io1, io2, io3, config);
pin_mut!(q);
let mut id = [1; 3]; let mut id = [1; 3];
q.as_mut() q.custom_instruction(0x9F, &[], &mut id).await.unwrap();
.custom_instruction(0x9F, &[], &mut id)
.await
.unwrap();
info!("id: {}", id); info!("id: {}", id);
// Read status register // Read status register
let mut status = [4; 1]; let mut status = [4; 1];
q.as_mut() q.custom_instruction(0x05, &[], &mut status).await.unwrap();
.custom_instruction(0x05, &[], &mut status)
.await
.unwrap();
info!("status: {:?}", status[0]); info!("status: {:?}", status[0]);
if status[0] & 0x40 == 0 { if status[0] & 0x40 == 0 {
status[0] |= 0x40; status[0] |= 0x40;
q.as_mut() q.custom_instruction(0x01, &status, &mut []).await.unwrap();
.custom_instruction(0x01, &status, &mut [])
.await
.unwrap();
info!("enabled quad in status"); info!("enabled quad in status");
} }
@ -72,19 +61,19 @@ async fn main(spawner: Spawner) {
for i in 0..8 { for i in 0..8 {
info!("page {:?}: erasing... ", i); info!("page {:?}: erasing... ", i);
q.as_mut().erase(i * PAGE_SIZE).await.unwrap(); q.erase(i * PAGE_SIZE).await.unwrap();
for j in 0..PAGE_SIZE { for j in 0..PAGE_SIZE {
buf.0[j] = pattern((j + i * PAGE_SIZE) as u32); buf.0[j] = pattern((j + i * PAGE_SIZE) as u32);
} }
info!("programming..."); info!("programming...");
q.as_mut().write(i * PAGE_SIZE, &buf.0).await.unwrap(); q.write(i * PAGE_SIZE, &buf.0).await.unwrap();
} }
for i in 0..8 { for i in 0..8 {
info!("page {:?}: reading... ", i); info!("page {:?}: reading... ", i);
q.as_mut().read(i * PAGE_SIZE, &mut buf.0).await.unwrap(); q.read(i * PAGE_SIZE, &mut buf.0).await.unwrap();
info!("verifying..."); info!("verifying...");
for j in 0..PAGE_SIZE { for j in 0..PAGE_SIZE {

View File

@ -17,7 +17,6 @@ use embassy_nrf::{interrupt, spim};
use embassy_traits::spi::FullDuplex; use embassy_traits::spi::FullDuplex;
use embedded_hal::digital::v2::*; use embedded_hal::digital::v2::*;
use example_common::*; use example_common::*;
use futures::pin_mut;
#[embassy::main] #[embassy::main]
async fn main(spawner: Spawner) { async fn main(spawner: Spawner) {
@ -32,8 +31,7 @@ async fn main(spawner: Spawner) {
}; };
let irq = interrupt::take!(SPIM3); let irq = interrupt::take!(SPIM3);
let spim = spim::Spim::new(p.SPIM3, irq, p.P0_29, p.P0_28, p.P0_30, config); let mut spim = spim::Spim::new(p.SPIM3, irq, p.P0_29, p.P0_28, p.P0_30, config);
pin_mut!(spim);
let mut ncs = Output::new(p.P0_31, Level::High, OutputDrive::Standard); let mut ncs = Output::new(p.P0_31, Level::High, OutputDrive::Standard);
@ -44,7 +42,7 @@ async fn main(spawner: Spawner) {
ncs.set_low().unwrap(); ncs.set_low().unwrap();
cortex_m::asm::delay(5); cortex_m::asm::delay(5);
let tx = [0xFF]; let tx = [0xFF];
unwrap!(spim.as_mut().read_write(&mut [], &tx).await); unwrap!(spim.read_write(&mut [], &tx).await);
cortex_m::asm::delay(10); cortex_m::asm::delay(10);
ncs.set_high().unwrap(); ncs.set_high().unwrap();
@ -57,7 +55,7 @@ async fn main(spawner: Spawner) {
ncs.set_low().unwrap(); ncs.set_low().unwrap();
cortex_m::asm::delay(5000); cortex_m::asm::delay(5000);
let tx = [0b000_11101, 0]; let tx = [0b000_11101, 0];
unwrap!(spim.as_mut().read_write(&mut rx, &tx).await); unwrap!(spim.read_write(&mut rx, &tx).await);
cortex_m::asm::delay(5000); cortex_m::asm::delay(5000);
ncs.set_high().unwrap(); ncs.set_high().unwrap();
info!("estat: {=[?]}", rx); info!("estat: {=[?]}", rx);
@ -67,7 +65,7 @@ async fn main(spawner: Spawner) {
ncs.set_low().unwrap(); ncs.set_low().unwrap();
cortex_m::asm::delay(5); cortex_m::asm::delay(5);
let tx = [0b100_11111, 0b11]; let tx = [0b100_11111, 0b11];
unwrap!(spim.as_mut().read_write(&mut rx, &tx).await); unwrap!(spim.read_write(&mut rx, &tx).await);
cortex_m::asm::delay(10); cortex_m::asm::delay(10);
ncs.set_high().unwrap(); ncs.set_high().unwrap();
@ -76,7 +74,7 @@ async fn main(spawner: Spawner) {
ncs.set_low().unwrap(); ncs.set_low().unwrap();
cortex_m::asm::delay(5); cortex_m::asm::delay(5);
let tx = [0b000_10010, 0]; let tx = [0b000_10010, 0];
unwrap!(spim.as_mut().read_write(&mut rx, &tx).await); unwrap!(spim.read_write(&mut rx, &tx).await);
cortex_m::asm::delay(10); cortex_m::asm::delay(10);
ncs.set_high().unwrap(); ncs.set_high().unwrap();

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

@ -1,7 +1,6 @@
use core::convert::Infallible; use core::convert::Infallible;
use core::future::Future; use core::future::Future;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::pin::Pin;
use core::task::{Context, Poll}; use core::task::{Context, Poll};
use embassy::interrupt::InterruptExt; use embassy::interrupt::InterruptExt;
use embassy::traits::gpio::{WaitForHigh, WaitForLow}; use embassy::traits::gpio::{WaitForHigh, WaitForLow};
@ -318,7 +317,7 @@ impl<'d, T: GpioPin> InputPin for PortInput<'d, T> {
impl<'d, T: GpioPin> WaitForHigh for PortInput<'d, T> { impl<'d, T: GpioPin> WaitForHigh for PortInput<'d, T> {
type Future<'a> = PortInputFuture<'a>; type Future<'a> = PortInputFuture<'a>;
fn wait_for_high<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_high<'a>(&'a mut self) -> Self::Future<'a> {
self.pin.pin.conf().modify(|_, w| w.sense().high()); self.pin.pin.conf().modify(|_, w| w.sense().high());
PortInputFuture { PortInputFuture {
@ -331,7 +330,7 @@ impl<'d, T: GpioPin> WaitForHigh for PortInput<'d, T> {
impl<'d, T: GpioPin> WaitForLow for PortInput<'d, T> { impl<'d, T: GpioPin> WaitForLow for PortInput<'d, T> {
type Future<'a> = PortInputFuture<'a>; type Future<'a> = PortInputFuture<'a>;
fn wait_for_low<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_low<'a>(&'a mut self) -> Self::Future<'a> {
self.pin.pin.conf().modify(|_, w| w.sense().low()); self.pin.pin.conf().modify(|_, w| w.sense().low());
PortInputFuture { PortInputFuture {

View File

@ -1,11 +1,11 @@
use core::future::Future; use core::future::Future;
use core::marker::PhantomData; use core::marker::PhantomData;
use core::pin::Pin;
use core::task::Poll; use core::task::Poll;
use embassy::interrupt::{Interrupt, InterruptExt};
use embassy::interrupt::Interrupt; use embassy::traits::flash::{Error, Flash};
use embassy_extras::peripheral::{PeripheralMutex, PeripheralState}; use embassy::util::{AtomicWaker, DropBomb, PeripheralBorrow};
use embassy_extras::unborrow; use embassy_extras::unborrow;
use futures::future::poll_fn;
use crate::fmt::{assert, assert_eq, *}; use crate::fmt::{assert, assert_eq, *};
use crate::gpio::Pin as GpioPin; use crate::gpio::Pin as GpioPin;
@ -27,10 +27,6 @@ pub use crate::pac::qspi::ifconfig0::WRITEOC_A as WriteOpcode;
// - activate/deactivate // - activate/deactivate
// - set gpio in high drive // - set gpio in high drive
use embassy::traits::flash::{Error, Flash};
use embassy::util::{wake_on_interrupt, DropBomb, PeripheralBorrow, WakerRegistration};
use futures::future::poll_fn;
pub struct DeepPowerDownConfig { pub struct DeepPowerDownConfig {
pub enter_time: u16, pub enter_time: u16,
pub exit_time: u16, pub exit_time: u16,
@ -77,7 +73,7 @@ impl<'d, T: Instance> Qspi<'d, T> {
) -> Self { ) -> Self {
unborrow!(qspi, irq, sck, csn, io0, io1, io2, io3); unborrow!(qspi, irq, sck, csn, io0, io1, io2, io3);
let r = qspi.regs(); let r = T::regs();
for cnf in &[ for cnf in &[
sck.conf(), sck.conf(),
@ -137,6 +133,10 @@ impl<'d, T: Instance> Qspi<'d, T> {
while r.events_ready.read().bits() == 0 {} while r.events_ready.read().bits() == 0 {}
r.events_ready.reset(); r.events_ready.reset();
irq.set_handler(Self::on_interrupt);
irq.unpend();
irq.enable();
Self { Self {
peri: qspi, peri: qspi,
irq, irq,
@ -144,8 +144,18 @@ impl<'d, T: Instance> Qspi<'d, T> {
} }
} }
pub fn sleep(mut self: Pin<&mut Self>) { fn on_interrupt(_: *mut ()) {
let r = unsafe { self.as_mut().get_unchecked_mut() }.peri.regs(); let r = T::regs();
let s = T::state();
if r.events_ready.read().bits() != 0 {
s.ready_waker.wake();
r.intenclr.write(|w| w.ready().clear());
}
}
pub fn sleep(&mut self) {
let r = T::regs();
info!("flash: sleeping"); info!("flash: sleeping");
info!("flash: state = {:?}", r.status.read().bits()); info!("flash: state = {:?}", r.status.read().bits());
@ -158,7 +168,7 @@ impl<'d, T: Instance> Qspi<'d, T> {
} }
pub async fn custom_instruction( pub async fn custom_instruction(
mut self: Pin<&mut Self>, &mut self,
opcode: u8, opcode: u8,
req: &[u8], req: &[u8],
resp: &mut [u8], resp: &mut [u8],
@ -184,7 +194,7 @@ impl<'d, T: Instance> Qspi<'d, T> {
let len = core::cmp::max(req.len(), resp.len()) as u8; let len = core::cmp::max(req.len(), resp.len()) as u8;
let r = unsafe { self.as_mut().get_unchecked_mut() }.peri.regs(); let r = T::regs();
r.cinstrdat0.write(|w| unsafe { w.bits(dat0) }); r.cinstrdat0.write(|w| unsafe { w.bits(dat0) });
r.cinstrdat1.write(|w| unsafe { w.bits(dat1) }); r.cinstrdat1.write(|w| unsafe { w.bits(dat1) });
@ -203,9 +213,9 @@ impl<'d, T: Instance> Qspi<'d, T> {
w w
}); });
self.as_mut().wait_ready().await; self.wait_ready().await;
let r = unsafe { self.as_mut().get_unchecked_mut() }.peri.regs(); let r = T::regs();
let dat0 = r.cinstrdat0.read().bits(); let dat0 = r.cinstrdat0.read().bits();
let dat1 = r.cinstrdat1.read().bits(); let dat1 = r.cinstrdat1.read().bits();
@ -225,19 +235,14 @@ impl<'d, T: Instance> Qspi<'d, T> {
Ok(()) Ok(())
} }
async fn wait_ready(self: Pin<&mut Self>) { async fn wait_ready(&mut self) {
let this = unsafe { self.get_unchecked_mut() };
poll_fn(move |cx| { poll_fn(move |cx| {
let r = this.peri.regs(); let r = T::regs();
let s = T::state();
s.ready_waker.register(cx.waker());
if r.events_ready.read().bits() != 0 { if r.events_ready.read().bits() != 0 {
r.events_ready.reset();
return Poll::Ready(()); return Poll::Ready(());
} }
wake_on_interrupt(&mut this.irq, cx.waker());
Poll::Pending Poll::Pending
}) })
.await .await
@ -252,11 +257,7 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
#[rustfmt::skip] #[rustfmt::skip]
type ErasePageFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a; type ErasePageFuture<'a> where Self: 'a = impl Future<Output = Result<(), Error>> + 'a;
fn read<'a>( fn read<'a>(&'a mut self, address: usize, data: &'a mut [u8]) -> Self::ReadFuture<'a> {
mut self: Pin<&'a mut Self>,
address: usize,
data: &'a mut [u8],
) -> Self::ReadFuture<'a> {
async move { async move {
let bomb = DropBomb::new(); let bomb = DropBomb::new();
@ -264,7 +265,7 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
assert_eq!(data.len() as u32 % 4, 0); assert_eq!(data.len() as u32 % 4, 0);
assert_eq!(address as u32 % 4, 0); assert_eq!(address as u32 % 4, 0);
let r = unsafe { self.as_mut().get_unchecked_mut() }.peri.regs(); let r = T::regs();
r.read r.read
.src .src
@ -280,7 +281,7 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
r.intenset.write(|w| w.ready().set()); r.intenset.write(|w| w.ready().set());
r.tasks_readstart.write(|w| w.tasks_readstart().bit(true)); r.tasks_readstart.write(|w| w.tasks_readstart().bit(true));
self.as_mut().wait_ready().await; self.wait_ready().await;
bomb.defuse(); bomb.defuse();
@ -288,11 +289,7 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
} }
} }
fn write<'a>( fn write<'a>(&'a mut self, address: usize, data: &'a [u8]) -> Self::WriteFuture<'a> {
mut self: Pin<&'a mut Self>,
address: usize,
data: &'a [u8],
) -> Self::WriteFuture<'a> {
async move { async move {
let bomb = DropBomb::new(); let bomb = DropBomb::new();
@ -300,7 +297,7 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
assert_eq!(data.len() as u32 % 4, 0); assert_eq!(data.len() as u32 % 4, 0);
assert_eq!(address as u32 % 4, 0); assert_eq!(address as u32 % 4, 0);
let r = unsafe { self.as_mut().get_unchecked_mut() }.peri.regs(); let r = T::regs();
r.write r.write
.src .src
.write(|w| unsafe { w.src().bits(data.as_ptr() as u32) }); .write(|w| unsafe { w.src().bits(data.as_ptr() as u32) });
@ -315,7 +312,7 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
r.intenset.write(|w| w.ready().set()); r.intenset.write(|w| w.ready().set());
r.tasks_writestart.write(|w| w.tasks_writestart().bit(true)); r.tasks_writestart.write(|w| w.tasks_writestart().bit(true));
self.as_mut().wait_ready().await; self.wait_ready().await;
bomb.defuse(); bomb.defuse();
@ -323,13 +320,13 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
} }
} }
fn erase<'a>(mut self: Pin<&'a mut Self>, address: usize) -> Self::ErasePageFuture<'a> { fn erase<'a>(&'a mut self, address: usize) -> Self::ErasePageFuture<'a> {
async move { async move {
let bomb = DropBomb::new(); let bomb = DropBomb::new();
assert_eq!(address as u32 % 4096, 0); assert_eq!(address as u32 % 4096, 0);
let r = unsafe { self.as_mut().get_unchecked_mut() }.peri.regs(); let r = T::regs();
r.erase r.erase
.ptr .ptr
.write(|w| unsafe { w.ptr().bits(address as u32) }); .write(|w| unsafe { w.ptr().bits(address as u32) });
@ -339,7 +336,7 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
r.intenset.write(|w| w.ready().set()); r.intenset.write(|w| w.ready().set());
r.tasks_erasestart.write(|w| w.tasks_erasestart().bit(true)); r.tasks_erasestart.write(|w| w.tasks_erasestart().bit(true));
self.as_mut().wait_ready().await; self.wait_ready().await;
bomb.defuse(); bomb.defuse();
@ -367,8 +364,20 @@ impl<'d, T: Instance> Flash for Qspi<'d, T> {
mod sealed { mod sealed {
use super::*; use super::*;
pub struct State {
pub ready_waker: AtomicWaker,
}
impl State {
pub const fn new() -> Self {
Self {
ready_waker: AtomicWaker::new(),
}
}
}
pub trait Instance { pub trait Instance {
fn regs(&self) -> &pac::qspi::RegisterBlock; fn regs() -> &'static pac::qspi::RegisterBlock;
fn state() -> &'static State;
} }
} }
@ -379,9 +388,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::qspi::RegisterBlock { fn regs() -> &'static pac::qspi::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

@ -1,10 +1,10 @@
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, Ordering};
use core::task::Poll; use core::task::Poll;
use embassy::interrupt::InterruptExt;
use embassy::traits; use embassy::traits;
use embassy::util::{wake_on_interrupt, PeripheralBorrow}; use embassy::util::{AtomicWaker, PeripheralBorrow};
use embassy_extras::unborrow; use embassy_extras::unborrow;
use futures::future::poll_fn; use futures::future::poll_fn;
use traits::spi::FullDuplex; use traits::spi::FullDuplex;
@ -50,7 +50,7 @@ impl<'d, T: Instance> Spim<'d, T> {
) -> Self { ) -> Self {
unborrow!(spim, irq, sck, miso, mosi); unborrow!(spim, irq, sck, miso, mosi);
let r = spim.regs(); let r = T::regs();
// Configure pins // Configure pins
sck.conf().write(|w| w.dir().output().drive().h0h1()); sck.conf().write(|w| w.dir().output().drive().h0h1());
@ -122,12 +122,26 @@ impl<'d, T: Instance> Spim<'d, T> {
// Disable all events interrupts // Disable all events interrupts
r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) }); r.intenclr.write(|w| unsafe { w.bits(0xFFFF_FFFF) });
irq.set_handler(Self::on_interrupt);
irq.unpend();
irq.enable();
Self { Self {
peri: spim, peri: spim,
irq, irq,
phantom: PhantomData, phantom: PhantomData,
} }
} }
fn on_interrupt(_: *mut ()) {
let r = T::regs();
let s = T::state();
if r.events_end.read().bits() != 0 {
s.end_waker.wake();
r.intenclr.write(|w| w.end().clear());
}
}
} }
impl<'d, T: Instance> FullDuplex<u8> for Spim<'d, T> { impl<'d, T: Instance> FullDuplex<u8> for Spim<'d, T> {
@ -140,20 +154,15 @@ impl<'d, T: Instance> FullDuplex<u8> for Spim<'d, T> {
#[rustfmt::skip] #[rustfmt::skip]
type WriteReadFuture<'a> where Self: 'a = impl Future<Output = Result<(), Self::Error>> + 'a; type WriteReadFuture<'a> where Self: 'a = impl Future<Output = Result<(), Self::Error>> + 'a;
fn read<'a>(self: Pin<&'a mut Self>, data: &'a mut [u8]) -> Self::ReadFuture<'a> { fn read<'a>(&'a mut self, data: &'a mut [u8]) -> Self::ReadFuture<'a> {
self.read_write(data, &[]) self.read_write(data, &[])
} }
fn write<'a>(self: Pin<&'a mut Self>, data: &'a [u8]) -> Self::WriteFuture<'a> { fn write<'a>(&'a mut self, data: &'a [u8]) -> Self::WriteFuture<'a> {
self.read_write(&mut [], data) self.read_write(&mut [], data)
} }
fn read_write<'a>( fn read_write<'a>(&'a mut self, rx: &'a mut [u8], tx: &'a [u8]) -> Self::WriteReadFuture<'a> {
self: Pin<&'a mut Self>,
rx: &'a mut [u8],
tx: &'a [u8],
) -> Self::WriteReadFuture<'a> {
async move { async move {
let this = unsafe { self.get_unchecked_mut() };
slice_in_ram_or(rx, Error::DMABufferNotInDataMemory)?; slice_in_ram_or(rx, Error::DMABufferNotInDataMemory)?;
slice_in_ram_or(tx, Error::DMABufferNotInDataMemory)?; slice_in_ram_or(tx, Error::DMABufferNotInDataMemory)?;
@ -162,7 +171,8 @@ impl<'d, T: Instance> FullDuplex<u8> for Spim<'d, T> {
// before any DMA action has started. // before any DMA action has started.
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
let r = this.peri.regs(); let r = T::regs();
let s = T::state();
// Set up the DMA write. // Set up the DMA write.
r.txd r.txd
@ -194,15 +204,11 @@ impl<'d, T: Instance> FullDuplex<u8> for Spim<'d, T> {
// Wait for 'end' event. // Wait for 'end' event.
poll_fn(|cx| { poll_fn(|cx| {
let r = this.peri.regs(); s.end_waker.register(cx.waker());
if r.events_end.read().bits() != 0 { if r.events_end.read().bits() != 0 {
r.events_end.reset();
return Poll::Ready(()); return Poll::Ready(());
} }
wake_on_interrupt(&mut this.irq, cx.waker());
Poll::Pending Poll::Pending
}) })
.await; .await;
@ -215,8 +221,21 @@ impl<'d, T: Instance> FullDuplex<u8> for Spim<'d, T> {
mod sealed { mod sealed {
use super::*; use super::*;
pub struct State {
pub end_waker: AtomicWaker,
}
impl State {
pub const fn new() -> Self {
Self {
end_waker: AtomicWaker::new(),
}
}
}
pub trait Instance { pub trait Instance {
fn regs(&self) -> &pac::spim0::RegisterBlock; fn regs() -> &'static pac::spim0::RegisterBlock;
fn state() -> &'static State;
} }
} }
@ -227,9 +246,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::spim0::RegisterBlock { fn regs() -> &'static pac::spim0::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,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(
irq,
State {
peri: uarte, 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

@ -26,13 +26,12 @@ async fn run(dp: stm32::Peripherals, _cp: cortex_m::Peripherals) {
let button = gpioa.pa0.into_pull_up_input(); let button = gpioa.pa0.into_pull_up_input();
let mut syscfg = dp.SYSCFG.constrain(); let mut syscfg = dp.SYSCFG.constrain();
let pin = ExtiPin::new(button, interrupt::take!(EXTI0), &mut syscfg); let mut pin = ExtiPin::new(button, interrupt::take!(EXTI0), &mut syscfg);
pin_mut!(pin);
info!("Starting loop"); info!("Starting loop");
loop { loop {
pin.as_mut().wait_for_rising_edge().await; pin.wait_for_rising_edge().await;
info!("edge detected!"); info!("edge detected!");
} }
} }

View File

@ -1,6 +1,5 @@
use core::future::Future; use core::future::Future;
use core::mem; use core::mem;
use core::pin::Pin;
use cortex_m; use cortex_m;
use crate::hal::gpio; use crate::hal::gpio;
@ -96,13 +95,10 @@ impl<T: Instance + digital::InputPin> digital::InputPin for ExtiPin<T> {
} }
impl<T: Instance + digital::InputPin + 'static> ExtiPin<T> { impl<T: Instance + digital::InputPin + 'static> ExtiPin<T> {
fn wait_for_state<'a>(self: Pin<&'a mut Self>, state: bool) -> impl Future<Output = ()> + 'a { fn wait_for_state<'a>(&'a mut self, state: bool) -> impl Future<Output = ()> + 'a {
let s = unsafe { self.get_unchecked_mut() };
s.pin.clear_pending_bit();
async move { async move {
let fut = InterruptFuture::new(&mut s.interrupt); let fut = InterruptFuture::new(&mut self.interrupt);
let pin = &mut s.pin; let pin = &mut self.pin;
cortex_m::interrupt::free(|_| { cortex_m::interrupt::free(|_| {
pin.trigger_edge(if state { pin.trigger_edge(if state {
EdgeOption::Rising EdgeOption::Rising
@ -111,37 +107,32 @@ impl<T: Instance + digital::InputPin + 'static> ExtiPin<T> {
}); });
}); });
if (state && s.pin.is_high().unwrap_or(false)) if (state && self.pin.is_high().unwrap_or(false))
|| (!state && s.pin.is_low().unwrap_or(false)) || (!state && self.pin.is_low().unwrap_or(false))
{ {
return; return;
} }
fut.await; fut.await;
s.pin.clear_pending_bit(); self.pin.clear_pending_bit();
} }
} }
} }
impl<T: Instance + 'static> ExtiPin<T> { impl<T: Instance + 'static> ExtiPin<T> {
fn wait_for_edge<'a>( fn wait_for_edge<'a>(&'a mut self, state: EdgeOption) -> impl Future<Output = ()> + 'a {
self: Pin<&'a mut Self>, self.pin.clear_pending_bit();
state: EdgeOption,
) -> impl Future<Output = ()> + 'a {
let s = unsafe { self.get_unchecked_mut() };
s.pin.clear_pending_bit();
async move { async move {
let fut = InterruptFuture::new(&mut s.interrupt); let fut = InterruptFuture::new(&mut self.interrupt);
let pin = &mut s.pin; let pin = &mut self.pin;
cortex_m::interrupt::free(|_| { cortex_m::interrupt::free(|_| {
pin.trigger_edge(state); pin.trigger_edge(state);
}); });
fut.await; fut.await;
s.pin.clear_pending_bit(); self.pin.clear_pending_bit();
} }
} }
} }
@ -149,7 +140,7 @@ impl<T: Instance + 'static> ExtiPin<T> {
impl<T: Instance + digital::InputPin + 'static> WaitForHigh for ExtiPin<T> { impl<T: Instance + digital::InputPin + 'static> WaitForHigh for ExtiPin<T> {
type Future<'a> = impl Future<Output = ()> + 'a; type Future<'a> = impl Future<Output = ()> + 'a;
fn wait_for_high<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_high<'a>(&'a mut self) -> Self::Future<'a> {
self.wait_for_state(true) self.wait_for_state(true)
} }
} }
@ -157,7 +148,7 @@ impl<T: Instance + digital::InputPin + 'static> WaitForHigh for ExtiPin<T> {
impl<T: Instance + digital::InputPin + 'static> WaitForLow for ExtiPin<T> { impl<T: Instance + digital::InputPin + 'static> WaitForLow for ExtiPin<T> {
type Future<'a> = impl Future<Output = ()> + 'a; type Future<'a> = impl Future<Output = ()> + 'a;
fn wait_for_low<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_low<'a>(&'a mut self) -> Self::Future<'a> {
self.wait_for_state(false) self.wait_for_state(false)
} }
} }
@ -176,7 +167,7 @@ impl<T: Instance + digital::InputPin + 'static> WaitForLow for ExtiPin<T> {
impl<T: Instance + 'static> WaitForRisingEdge for ExtiPin<T> { impl<T: Instance + 'static> WaitForRisingEdge for ExtiPin<T> {
type Future<'a> = impl Future<Output = ()> + 'a; type Future<'a> = impl Future<Output = ()> + 'a;
fn wait_for_rising_edge<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_rising_edge<'a>(&'a mut self) -> Self::Future<'a> {
self.wait_for_edge(EdgeOption::Rising) self.wait_for_edge(EdgeOption::Rising)
} }
} }
@ -184,7 +175,7 @@ impl<T: Instance + 'static> WaitForRisingEdge for ExtiPin<T> {
impl<T: Instance + 'static> WaitForFallingEdge for ExtiPin<T> { impl<T: Instance + 'static> WaitForFallingEdge for ExtiPin<T> {
type Future<'a> = impl Future<Output = ()> + 'a; type Future<'a> = impl Future<Output = ()> + 'a;
fn wait_for_falling_edge<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_falling_edge<'a>(&'a mut self) -> Self::Future<'a> {
self.wait_for_edge(EdgeOption::Falling) self.wait_for_edge(EdgeOption::Falling)
} }
} }
@ -192,7 +183,7 @@ impl<T: Instance + 'static> WaitForFallingEdge for ExtiPin<T> {
impl<T: Instance + 'static> WaitForAnyEdge for ExtiPin<T> { impl<T: Instance + 'static> WaitForAnyEdge for ExtiPin<T> {
type Future<'a> = impl Future<Output = ()> + 'a; type Future<'a> = impl Future<Output = ()> + 'a;
fn wait_for_any_edge<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_any_edge<'a>(&'a mut self) -> Self::Future<'a> {
self.wait_for_edge(EdgeOption::RisingFalling) self.wait_for_edge(EdgeOption::RisingFalling)
} }
} }

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

@ -214,14 +214,13 @@ where
type ReadFuture<'a> = impl Future<Output = Result<(), Error>> + 'a; type ReadFuture<'a> = impl Future<Output = Result<(), Error>> + 'a;
type WriteReadFuture<'a> = impl Future<Output = Result<(), Error>> + 'a; type WriteReadFuture<'a> = impl Future<Output = Result<(), Error>> + '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> {
let this = unsafe { self.get_unchecked_mut() };
#[allow(mutable_transmutes)] #[allow(mutable_transmutes)]
let static_buf: &'static mut [u8] = unsafe { mem::transmute(buf) }; let static_buf: &'static mut [u8] = unsafe { mem::transmute(buf) };
async move { async move {
let rx_stream = this.rx_stream.take().unwrap(); let rx_stream = self.rx_stream.take().unwrap();
let spi = this.spi.take().unwrap(); let spi = self.spi.take().unwrap();
spi.cr2.modify(|_, w| w.errie().set_bit()); spi.cr2.modify(|_, w| w.errie().set_bit());
@ -236,8 +235,8 @@ where
.double_buffer(false), .double_buffer(false),
); );
let fut = InterruptFuture::new(&mut this.rx_int); let fut = InterruptFuture::new(&mut self.rx_int);
let fut_err = InterruptFuture::new(&mut this.spi_int); let fut_err = InterruptFuture::new(&mut self.spi_int);
rx_transfer.start(|_spi| {}); rx_transfer.start(|_spi| {});
future::select(fut, fut_err).await; future::select(fut, fut_err).await;
@ -245,21 +244,20 @@ where
let (rx_stream, spi, _buf, _) = rx_transfer.free(); let (rx_stream, spi, _buf, _) = rx_transfer.free();
spi.cr2.modify(|_, w| w.errie().clear_bit()); spi.cr2.modify(|_, w| w.errie().clear_bit());
this.rx_stream.replace(rx_stream); self.rx_stream.replace(rx_stream);
this.spi.replace(spi); self.spi.replace(spi);
Ok(()) Ok(())
} }
} }
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: &'static mut [u8] = unsafe { mem::transmute(buf) }; let static_buf: &'static mut [u8] = unsafe { mem::transmute(buf) };
async move { async move {
let tx_stream = this.tx_stream.take().unwrap(); let tx_stream = self.tx_stream.take().unwrap();
let spi = this.spi.take().unwrap(); let spi = self.spi.take().unwrap();
// let mut tx_transfer = Transfer::init( // let mut tx_transfer = Transfer::init(
// tx_stream, // tx_stream,
@ -272,7 +270,7 @@ 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(|_spi| {}); // tx_transfer.start(|_spi| {});
// fut.await; // fut.await;
@ -284,28 +282,26 @@ where
nb::block!(write_sr(&spi, byte)); nb::block!(write_sr(&spi, byte));
} }
this.tx_stream.replace(tx_stream); self.tx_stream.replace(tx_stream);
this.spi.replace(spi); self.spi.replace(spi);
Ok(()) Ok(())
} }
} }
fn read_write<'a>( fn read_write<'a>(
self: Pin<&'a mut Self>, &'a mut self,
read_buf: &'a mut [u8], read_buf: &'a mut [u8],
write_buf: &'a [u8], write_buf: &'a [u8],
) -> Self::WriteReadFuture<'a> { ) -> Self::WriteReadFuture<'a> {
let this = unsafe { self.get_unchecked_mut() };
#[allow(mutable_transmutes)] #[allow(mutable_transmutes)]
let write_static_buf: &'static mut [u8] = unsafe { mem::transmute(write_buf) }; let write_static_buf: &'static mut [u8] = unsafe { mem::transmute(write_buf) };
let read_static_buf: &'static mut [u8] = unsafe { mem::transmute(read_buf) }; let read_static_buf: &'static mut [u8] = unsafe { mem::transmute(read_buf) };
async move { async move {
let tx_stream = this.tx_stream.take().unwrap(); let tx_stream = self.tx_stream.take().unwrap();
let rx_stream = this.rx_stream.take().unwrap(); let rx_stream = self.rx_stream.take().unwrap();
let spi_tx = this.spi.take().unwrap(); let spi_tx = self.spi.take().unwrap();
let spi_rx: SPI = unsafe { mem::transmute_copy(&spi_tx) }; let spi_rx: SPI = unsafe { mem::transmute_copy(&spi_tx) };
spi_rx spi_rx
@ -334,9 +330,9 @@ where
// .double_buffer(false), // .double_buffer(false),
// ); // );
// //
// let tx_fut = InterruptFuture::new(&mut this.tx_int); // let tx_fut = InterruptFuture::new(&mut self.tx_int);
// let rx_fut = InterruptFuture::new(&mut this.rx_int); // let rx_fut = InterruptFuture::new(&mut self.rx_int);
// let rx_fut_err = InterruptFuture::new(&mut this.spi_int); // let rx_fut_err = InterruptFuture::new(&mut self.spi_int);
// //
// rx_transfer.start(|_spi| {}); // rx_transfer.start(|_spi| {});
// tx_transfer.start(|_spi| {}); // tx_transfer.start(|_spi| {});
@ -352,7 +348,7 @@ where
for i in 0..(read_static_buf.len() - 1) { for i in 0..(read_static_buf.len() - 1) {
let byte = write_static_buf[i]; let byte = write_static_buf[i];
loop { loop {
let fut = InterruptFuture::new(&mut this.spi_int); let fut = InterruptFuture::new(&mut self.spi_int);
match write_sr(&spi_tx, byte) { match write_sr(&spi_tx, byte) {
Ok(()) => break, Ok(()) => break,
_ => {} _ => {}
@ -361,7 +357,7 @@ where
} }
loop { loop {
let fut = InterruptFuture::new(&mut this.spi_int); let fut = InterruptFuture::new(&mut self.spi_int);
match read_sr(&spi_tx) { match read_sr(&spi_tx) {
Ok(byte) => { Ok(byte) => {
read_static_buf[i] = byte; read_static_buf[i] = byte;
@ -381,9 +377,9 @@ where
.rxneie() .rxneie()
.clear_bit() .clear_bit()
}); });
this.rx_stream.replace(rx_stream); self.rx_stream.replace(rx_stream);
this.tx_stream.replace(tx_stream); self.tx_stream.replace(tx_stream);
this.spi.replace(spi_rx); self.spi.replace(spi_rx);
Ok(()) Ok(())
} }
@ -421,7 +417,7 @@ macro_rules! spi {
impl Instance for pac::$SPI { impl Instance for pac::$SPI {
unsafe fn enable_clock() { unsafe fn enable_clock() {
const EN_BIT: u8 = $en; const EN_BIT: u8 = $en;
// NOTE(unsafe) this reference will only be used for atomic writes with no side effects. // NOTE(unsafe) self reference will only be used for atomic writes with no side effects.
let rcc = &(*pac::RCC::ptr()); let rcc = &(*pac::RCC::ptr());
// Enable clock. // Enable clock.
bb::set(&rcc.$apbXenr, EN_BIT); bb::set(&rcc.$apbXenr, EN_BIT);

View File

@ -1,12 +1,11 @@
use core::future::Future; use core::future::Future;
use core::pin::Pin;
pub trait Delay { pub trait Delay {
type DelayFuture<'a>: Future<Output = ()> + 'a; type DelayFuture<'a>: Future<Output = ()> + 'a;
/// Future that completes after now + millis /// Future that completes after now + millis
fn delay_ms<'a>(self: Pin<&'a mut Self>, millis: u64) -> Self::DelayFuture<'a>; fn delay_ms<'a>(&'a mut self, millis: u64) -> Self::DelayFuture<'a>;
/// Future that completes after now + micros /// Future that completes after now + micros
fn delay_us<'a>(self: Pin<&'a mut Self>, micros: u64) -> Self::DelayFuture<'a>; fn delay_us<'a>(&'a mut self, micros: u64) -> Self::DelayFuture<'a>;
} }

View File

@ -27,19 +27,18 @@ pub trait Flash {
/// ///
/// address must be a multiple of self.read_size(). /// address must be a multiple of self.read_size().
/// buf.len() must be a multiple of self.read_size(). /// buf.len() must be a multiple of self.read_size().
fn read<'a>(self: Pin<&'a mut Self>, address: usize, buf: &'a mut [u8]) fn read<'a>(&'a mut self, address: usize, buf: &'a mut [u8]) -> Self::ReadFuture<'a>;
-> Self::ReadFuture<'a>;
/// Writes data to the flash device. /// Writes data to the flash device.
/// ///
/// address must be a multiple of self.write_size(). /// address must be a multiple of self.write_size().
/// buf.len() must be a multiple of self.write_size(). /// buf.len() must be a multiple of self.write_size().
fn write<'a>(self: Pin<&'a mut Self>, address: usize, buf: &'a [u8]) -> Self::WriteFuture<'a>; fn write<'a>(&'a mut self, address: usize, buf: &'a [u8]) -> Self::WriteFuture<'a>;
/// Erases a single page from the flash device. /// Erases a single page from the flash device.
/// ///
/// address must be a multiple of self.erase_size(). /// address must be a multiple of self.erase_size().
fn erase<'a>(self: Pin<&'a mut Self>, address: usize) -> Self::ErasePageFuture<'a>; fn erase<'a>(&'a mut self, address: usize) -> Self::ErasePageFuture<'a>;
/// Returns the total size, in bytes. /// Returns the total size, in bytes.
/// This is not guaranteed to be a power of 2. /// This is not guaranteed to be a power of 2.

View File

@ -9,7 +9,7 @@ pub trait WaitForHigh {
/// ///
/// If the pin is already high, the future completes immediately. /// If the pin is already high, the future completes immediately.
/// Otherwise, it completes when it becomes high. /// Otherwise, it completes when it becomes high.
fn wait_for_high<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a>; fn wait_for_high<'a>(&'a mut self) -> Self::Future<'a>;
} }
/// Wait for a pin to become low. /// Wait for a pin to become low.
@ -20,7 +20,7 @@ pub trait WaitForLow {
/// ///
/// If the pin is already low, the future completes immediately. /// If the pin is already low, the future completes immediately.
/// Otherwise, it completes when it becomes low. /// Otherwise, it completes when it becomes low.
fn wait_for_low<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a>; fn wait_for_low<'a>(&'a mut self) -> Self::Future<'a>;
} }
/// Wait for a rising edge (transition from low to high) /// Wait for a rising edge (transition from low to high)
@ -28,7 +28,7 @@ pub trait WaitForRisingEdge {
type Future<'a>: Future<Output = ()> + 'a; type Future<'a>: Future<Output = ()> + 'a;
/// Wait for a rising edge (transition from low to high) /// Wait for a rising edge (transition from low to high)
fn wait_for_rising_edge<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a>; fn wait_for_rising_edge<'a>(&'a mut self) -> Self::Future<'a>;
} }
/// Wait for a falling edge (transition from high to low) /// Wait for a falling edge (transition from high to low)
@ -36,7 +36,7 @@ pub trait WaitForFallingEdge {
type Future<'a>: Future<Output = ()> + 'a; type Future<'a>: Future<Output = ()> + 'a;
/// Wait for a falling edge (transition from high to low) /// Wait for a falling edge (transition from high to low)
fn wait_for_falling_edge<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a>; fn wait_for_falling_edge<'a>(&'a mut self) -> Self::Future<'a>;
} }
/// Wait for any edge (any transition, high to low or low to high) /// Wait for any edge (any transition, high to low or low to high)
@ -44,5 +44,5 @@ pub trait WaitForAnyEdge {
type Future<'a>: Future<Output = ()> + 'a; type Future<'a>: Future<Output = ()> + 'a;
/// Wait for any edge (any transition, high to low or low to high) /// Wait for any edge (any transition, high to low or low to high)
fn wait_for_any_edge<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a>; fn wait_for_any_edge<'a>(&'a mut self) -> Self::Future<'a>;
} }

View File

@ -67,7 +67,6 @@
//! ``` //! ```
use core::future::Future; use core::future::Future;
use core::pin::Pin;
mod private { mod private {
pub trait Sealed {} pub trait Sealed {}
@ -117,7 +116,7 @@ pub trait I2c<A: AddressMode = SevenBitAddress> {
/// - `MAK` = master acknowledge /// - `MAK` = master acknowledge
/// - `NMAK` = master no acknowledge /// - `NMAK` = master no acknowledge
/// - `SP` = stop condition /// - `SP` = stop condition
fn read<'a>(self: Pin<&'a mut Self>, address: A, buffer: &mut [u8]) -> Self::ReadFuture<'a>; fn read<'a>(&'a mut self, address: A, buffer: &mut [u8]) -> Self::ReadFuture<'a>;
/// Sends bytes to slave with address `address` /// Sends bytes to slave with address `address`
/// ///
@ -135,7 +134,7 @@ pub trait I2c<A: AddressMode = SevenBitAddress> {
/// - `SAK` = slave acknowledge /// - `SAK` = slave acknowledge
/// - `Bi` = ith byte of data /// - `Bi` = ith byte of data
/// - `SP` = stop condition /// - `SP` = stop condition
fn write<'a>(self: Pin<&'a mut Self>, address: A, bytes: &[u8]) -> Self::WriteFuture<'a>; fn write<'a>(&'a mut self, address: A, bytes: &[u8]) -> Self::WriteFuture<'a>;
/// Sends bytes to slave with address `address` and then reads enough bytes to fill `buffer` *in a /// Sends bytes to slave with address `address` and then reads enough bytes to fill `buffer` *in a
/// single transaction* /// single transaction*
@ -160,7 +159,7 @@ pub trait I2c<A: AddressMode = SevenBitAddress> {
/// - `NMAK` = master no acknowledge /// - `NMAK` = master no acknowledge
/// - `SP` = stop condition /// - `SP` = stop condition
fn write_read<'a>( fn write_read<'a>(
self: Pin<&'a mut Self>, &'a mut self,
address: A, address: A,
bytes: &[u8], bytes: &[u8],
buffer: &mut [u8], buffer: &mut [u8],

View File

@ -33,10 +33,10 @@ pub trait FullDuplex<Word> {
where where
Self: 'a; Self: 'a;
fn read<'a>(self: Pin<&'a mut Self>, data: &'a mut [Word]) -> Self::ReadFuture<'a>; fn read<'a>(&'a mut self, data: &'a mut [Word]) -> Self::ReadFuture<'a>;
fn write<'a>(self: Pin<&'a mut Self>, data: &'a [Word]) -> Self::WriteFuture<'a>; fn write<'a>(&'a mut self, data: &'a [Word]) -> Self::WriteFuture<'a>;
fn read_write<'a>( fn read_write<'a>(
self: Pin<&'a mut Self>, &'a mut self,
read: &'a mut [Word], read: &'a mut [Word],
write: &'a [Word], write: &'a [Word],
) -> Self::WriteReadFuture<'a>; ) -> Self::WriteReadFuture<'a>;

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>;
} }

View File

@ -23,10 +23,10 @@ impl Delay {
impl crate::traits::delay::Delay for Delay { impl crate::traits::delay::Delay for Delay {
type DelayFuture<'a> = impl Future<Output = ()> + 'a; type DelayFuture<'a> = impl Future<Output = ()> + 'a;
fn delay_ms<'a>(self: Pin<&'a mut Self>, millis: u64) -> Self::DelayFuture<'a> { fn delay_ms<'a>(&'a mut self, millis: u64) -> Self::DelayFuture<'a> {
Timer::after(Duration::from_millis(millis)) Timer::after(Duration::from_millis(millis))
} }
fn delay_us<'a>(self: Pin<&'a mut Self>, micros: u64) -> Self::DelayFuture<'a> { fn delay_us<'a>(&'a mut self, micros: u64) -> Self::DelayFuture<'a> {
Timer::after(Duration::from_micros(micros)) Timer::after(Duration::from_micros(micros))
} }
} }