nrf/gpiote: update to new gpio

This commit is contained in:
Dario Nieuwenhuis 2021-03-20 03:09:42 +01:00
parent 3d3e770b8d
commit ba7b3974bb
3 changed files with 142 additions and 176 deletions

View File

@ -6,7 +6,9 @@
#[path = "../example_common.rs"] #[path = "../example_common.rs"]
mod example_common; mod example_common;
use embassy_nrf::gpio::{AnyPin, Input, Pin as _, Pull};
use example_common::*; use example_common::*;
use gpiote::GpioteInput;
use core::pin::Pin; use core::pin::Pin;
use cortex_m_rt::entry; use cortex_m_rt::entry;
@ -16,10 +18,10 @@ use nrf52840_hal::gpio;
use embassy::executor::{task, Executor}; use embassy::executor::{task, Executor};
use embassy::traits::gpio::{WaitForHigh, WaitForLow}; use embassy::traits::gpio::{WaitForHigh, WaitForLow};
use embassy::util::Forever; use embassy::util::Forever;
use embassy_nrf::gpiote::{Gpiote, GpiotePin}; use embassy_nrf::gpiote;
use embassy_nrf::interrupt; use embassy_nrf::interrupt;
async fn button(n: usize, mut pin: GpiotePin<gpio::PullUp>) { async fn button(n: usize, mut pin: GpioteInput<AnyPin>) {
loop { loop {
Pin::new(&mut pin).wait_for_low().await; Pin::new(&mut pin).wait_for_low().await;
info!("Button {:?} pressed!", n); info!("Button {:?} pressed!", n);
@ -30,26 +32,25 @@ async fn button(n: usize, mut pin: GpiotePin<gpio::PullUp>) {
#[task] #[task]
async fn run() { async fn run() {
let p = unwrap!(embassy_nrf::pac::Peripherals::take()); let p = unsafe { embassy_nrf::peripherals::Peripherals::steal() };
let port0 = gpio::p0::Parts::new(p.P0);
let (g, _) = Gpiote::new(p.GPIOTE, interrupt::take!(GPIOTE)); let g = gpiote::initialize(p.gpiote, interrupt::take!(GPIOTE));
let button1 = button( let button1 = button(
1, 1,
GpiotePin::new(g, port0.p0_11.into_pullup_input().degrade()), GpioteInput::new(g, Input::new(p.p0_11.degrade(), Pull::Up)),
); );
let button2 = button( let button2 = button(
2, 2,
GpiotePin::new(g, port0.p0_12.into_pullup_input().degrade()), GpioteInput::new(g, Input::new(p.p0_12.degrade(), Pull::Up)),
); );
let button3 = button( let button3 = button(
3, 3,
GpiotePin::new(g, port0.p0_24.into_pullup_input().degrade()), GpioteInput::new(g, Input::new(p.p0_24.degrade(), Pull::Up)),
); );
let button4 = button( let button4 = button(
4, 4,
GpiotePin::new(g, port0.p0_25.into_pullup_input().degrade()), GpioteInput::new(g, Input::new(p.p0_25.degrade(), Pull::Up)),
); );
futures::join!(button1, button2, button3, button4); futures::join!(button1, button2, button3, button4);
} }

View File

@ -30,7 +30,7 @@ pub enum Pull {
/// GPIO input driver. /// GPIO input driver.
pub struct Input<T: Pin> { pub struct Input<T: Pin> {
pin: T, pub(crate) pin: T,
} }
impl<T: Pin> Input<T> { impl<T: Pin> Input<T> {
@ -273,10 +273,8 @@ pub struct AnyPin {
} }
impl AnyPin { impl AnyPin {
pub unsafe fn steal_from_psel_bits(psel_bits: u32) -> Self { pub unsafe fn steal(pin_port: u8) -> Self {
Self { Self { pin_port }
pin_port: psel_bits as u8,
}
} }
} }

View File

@ -1,19 +1,24 @@
use core::convert::Infallible;
use core::future::Future; use core::future::Future;
use core::mem::ManuallyDrop; use core::intrinsics::transmute;
use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop};
use core::ops::Deref; use core::ops::Deref;
use core::pin::Pin; use core::pin::Pin;
use core::ptr; use core::ptr;
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};
use embassy::util::Signal; use embassy::util::{AtomicWakerRegistration, Signal};
use embedded_hal::digital::v2::{InputPin, OutputPin, StatefulOutputPin};
use crate::hal::gpio::{Input, Level, Output, Pin as GpioPin, Port}; use crate::gpio::sealed::Pin as _;
use crate::interrupt; use crate::gpio::{AnyPin, Input, Pin as GpioPin, Pull};
use crate::pac; use crate::pac;
use crate::pac::generic::Reg; use crate::pac::generic::Reg;
use crate::pac::gpiote::_TASKS_OUT; use crate::pac::gpiote::_TASKS_OUT;
use crate::pac::{p0 as pac_gpio, GPIOTE}; use crate::pac::p0 as pac_gpio;
use crate::{interrupt, peripherals};
#[cfg(not(feature = "51"))] #[cfg(not(feature = "51"))]
use crate::pac::gpiote::{_TASKS_CLR, _TASKS_SET}; use crate::pac::gpiote::{_TASKS_CLR, _TASKS_SET};
@ -63,12 +68,9 @@ impl ChannelID for ChAny {
} }
} }
#[derive(Clone, Copy)] const NEW_AWR: AtomicWakerRegistration = AtomicWakerRegistration::new();
pub struct Gpiote(()); static CHANNEL_WAKERS: [AtomicWakerRegistration; CHANNEL_COUNT] = [NEW_AWR; CHANNEL_COUNT];
static PORT_WAKERS: [AtomicWakerRegistration; PIN_COUNT] = [NEW_AWR; PIN_COUNT];
const NEW_SIGNAL: Signal<()> = Signal::new();
static CHANNEL_SIGNALS: [Signal<()>; CHANNEL_COUNT] = [NEW_SIGNAL; CHANNEL_COUNT];
static PORT_SIGNALS: [Signal<()>; PIN_COUNT] = [NEW_SIGNAL; PIN_COUNT];
pub enum InputChannelPolarity { pub enum InputChannelPolarity {
None, None,
@ -84,117 +86,84 @@ pub enum OutputChannelPolarity {
Toggle, Toggle,
} }
#[derive(Debug, Copy, Clone, Eq, PartialEq)] /// Token indicating GPIOTE has been correctly initialized.
#[cfg_attr(feature = "defmt", derive(defmt::Format))] ///
pub enum NewChannelError { /// This is not an owned singleton, it is Copy. Drivers that make use of GPIOTE require it.
NoFreeChannels, #[derive(Clone, Copy)]
pub struct Initialized {
_private: (),
} }
pub struct Channels { pub fn initialize(gpiote: peripherals::GPIOTE, irq: interrupt::GPIOTE) -> Initialized {
pub ch0: Ch0, #[cfg(any(feature = "52833", feature = "52840"))]
pub ch1: Ch1, let ports = unsafe { &[&*pac::P0::ptr(), &*pac::P1::ptr()] };
pub ch2: Ch2, #[cfg(not(any(feature = "52833", feature = "52840")))]
pub ch3: Ch3, let ports = unsafe { &[&*pac::P0::ptr()] };
pub ch4: Ch4,
pub ch5: Ch5, for &p in ports {
pub ch6: Ch6, // Enable latched detection
pub ch7: Ch7, p.detectmode.write(|w| w.detectmode().ldetect());
// Clear latch
p.latch.write(|w| unsafe { w.bits(0xFFFFFFFF) })
}
// Enable interrupts
let g = unsafe { &*pac::GPIOTE::ptr() };
g.events_port.write(|w| w);
g.intenset.write(|w| w.port().set());
irq.set_handler(on_irq);
irq.unpend();
irq.enable();
Initialized { _private: () }
} }
impl Gpiote { unsafe fn on_irq(_ctx: *mut ()) {
pub fn new(gpiote: GPIOTE, irq: interrupt::GPIOTE) -> (Self, Channels) { let g = &*pac::GPIOTE::ptr();
for i in 0..CHANNEL_COUNT {
if g.events_in[i].read().bits() != 0 {
g.events_in[i].write(|w| w);
CHANNEL_WAKERS[i].wake();
}
}
if g.events_port.read().bits() != 0 {
g.events_port.write(|w| w);
#[cfg(any(feature = "52833", feature = "52840"))] #[cfg(any(feature = "52833", feature = "52840"))]
let ports = unsafe { &[&*pac::P0::ptr(), &*pac::P1::ptr()] }; let ports = &[&*pac::P0::ptr(), &*pac::P1::ptr()];
#[cfg(not(any(feature = "52833", feature = "52840")))] #[cfg(not(any(feature = "52833", feature = "52840")))]
let ports = unsafe { &[&*pac::P0::ptr()] }; let ports = &[&*pac::P0::ptr()];
for &p in ports { for (port, &p) in ports.iter().enumerate() {
// Enable latched detection let bits = p.latch.read().bits();
p.detectmode.write(|w| w.detectmode().ldetect()); for pin in BitIter(bits) {
// Clear latch p.pin_cnf[pin as usize].modify(|_, w| w.sense().disabled());
p.latch.write(|w| unsafe { w.bits(0xFFFFFFFF) }) PORT_WAKERS[port * 32 + pin as usize].wake();
}
// Enable interrupts
gpiote.events_port.write(|w| w);
gpiote.intenset.write(|w| w.port().set());
irq.set_handler(Self::on_irq);
irq.unpend();
irq.enable();
(
Self(()),
Channels {
ch0: Ch0(()),
ch1: Ch1(()),
ch2: Ch2(()),
ch3: Ch3(()),
ch4: Ch4(()),
ch5: Ch5(()),
ch6: Ch6(()),
ch7: Ch7(()),
},
)
}
unsafe fn on_irq(_ctx: *mut ()) {
let g = &*GPIOTE::ptr();
for (event_in, signal) in g.events_in.iter().zip(CHANNEL_SIGNALS.iter()) {
if event_in.read().bits() != 0 {
event_in.write(|w| w);
signal.signal(());
} }
p.latch.write(|w| w.bits(bits));
} }
}
}
if g.events_port.read().bits() != 0 { struct BitIter(u32);
g.events_port.write(|w| w);
#[cfg(any(feature = "52833", feature = "52840"))] impl Iterator for BitIter {
let ports = &[&*pac::P0::ptr(), &*pac::P1::ptr()]; type Item = u32;
#[cfg(not(any(feature = "52833", feature = "52840")))]
let ports = &[&*pac::P0::ptr()];
let mut work = true; fn next(&mut self) -> Option<Self::Item> {
while work { match self.0.trailing_zeros() {
work = false; 32 => None,
for (port, &p) in ports.iter().enumerate() { b => {
for pin in BitIter(p.latch.read().bits()) { self.0 &= !(1 << b);
work = true; Some(b)
p.pin_cnf[pin as usize].modify(|_, w| w.sense().disabled());
p.latch.write(|w| w.bits(1 << pin));
PORT_SIGNALS[port * 32 + pin as usize].signal(());
}
}
} }
} }
} }
} }
fn pin_num<T>(pin: &GpioPin<T>) -> usize { /*
let port = match pin.port() {
Port::Port0 => 0,
#[cfg(any(feature = "52833", feature = "52840"))]
Port::Port1 => 32,
};
port + pin.pin() as usize
}
fn pin_block<T>(pin: &GpioPin<T>) -> &pac_gpio::RegisterBlock {
let ptr = match pin.port() {
Port::Port0 => pac::P0::ptr(),
#[cfg(any(feature = "52833", feature = "52840"))]
Port::Port1 => pac::P1::ptr(),
};
unsafe { &*ptr }
}
fn pin_conf<T>(pin: &GpioPin<T>) -> &pac_gpio::PIN_CNF {
&pin_block(pin).pin_cnf[pin.pin() as usize]
}
pub struct InputChannel<C: ChannelID, T> { pub struct InputChannel<C: ChannelID, T> {
ch: C, ch: C,
pin: GpioPin<Input<T>>, pin: GpioPin<Input<T>>,
@ -211,7 +180,7 @@ impl<C: ChannelID, T> Drop for InputChannel<C, T> {
impl<C: ChannelID, T> InputChannel<C, T> { impl<C: ChannelID, T> InputChannel<C, T> {
pub fn new( pub fn new(
_gpiote: Gpiote, _init: Initialized,
ch: C, ch: C,
pin: GpioPin<Input<T>>, pin: GpioPin<Input<T>>,
polarity: InputChannelPolarity, polarity: InputChannelPolarity,
@ -234,7 +203,7 @@ impl<C: ChannelID, T> InputChannel<C, T> {
unsafe { w.psel().bits(pin.pin()) } unsafe { w.psel().bits(pin.pin()) }
}); });
CHANNEL_SIGNALS[index].reset(); CHANNEL_WAKERS[index].reset();
// Enable interrupt // Enable interrupt
g.intenset.write(|w| unsafe { w.bits(1 << index) }); g.intenset.write(|w| unsafe { w.bits(1 << index) });
@ -251,7 +220,7 @@ impl<C: ChannelID, T> InputChannel<C, T> {
pub async fn wait(&self) { pub async fn wait(&self) {
let index = self.ch.number(); let index = self.ch.number();
CHANNEL_SIGNALS[index].wait().await; CHANNEL_WAKERS[index].wait().await;
} }
pub fn pin(&self) -> &GpioPin<Input<T>> { pub fn pin(&self) -> &GpioPin<Input<T>> {
@ -366,89 +335,87 @@ impl<C: ChannelID, T> OutputChannel<C, T> {
&g.tasks_set[index] &g.tasks_set[index]
} }
} }
*/
struct BitIter(u32); /// GPIO input driver with support
pub struct GpioteInput<T: GpioPin> {
impl Iterator for BitIter { pin: Input<T>,
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
match self.0.trailing_zeros() {
32 => None,
b => {
self.0 &= !(1 << b);
Some(b)
}
}
}
} }
impl<T: GpioPin> Unpin for GpioteInput<T> {}
pub struct GpiotePin<T> { impl<T: GpioPin> GpioteInput<T> {
pin: GpioPin<Input<T>>, pub fn new(_init: Initialized, pin: Input<T>) -> Self {
}
impl<T> Unpin for GpiotePin<T> {}
impl<T> GpiotePin<T> {
pub fn new(_gpiote: Gpiote, pin: GpioPin<Input<T>>) -> Self {
Self { pin } Self { pin }
} }
} }
impl<T: 'static> WaitForHigh for GpiotePin<T> { impl<T: GpioPin> InputPin for GpioteInput<T> {
type Future<'a> = PortInputFuture<'a, T>; type Error = Infallible;
fn is_high(&self) -> Result<bool, Self::Error> {
self.pin.is_high()
}
fn is_low(&self) -> Result<bool, Self::Error> {
self.pin.is_low()
}
}
impl<T: GpioPin> WaitForHigh for GpioteInput<T> {
type Future<'a> = PortInputFuture<'a>;
fn wait_for_high<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_high<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> {
self.pin.pin.conf().modify(|_, w| w.sense().high());
PortInputFuture { PortInputFuture {
pin: &self.get_mut().pin, pin_port: self.pin.pin.pin_port(),
polarity: PortInputPolarity::High, phantom: PhantomData,
} }
} }
} }
impl<T: 'static> WaitForLow for GpiotePin<T> { impl<T: GpioPin> WaitForLow for GpioteInput<T> {
type Future<'a> = PortInputFuture<'a, T>; type Future<'a> = PortInputFuture<'a>;
fn wait_for_low<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> { fn wait_for_low<'a>(self: Pin<&'a mut Self>) -> Self::Future<'a> {
self.pin.pin.conf().modify(|_, w| w.sense().low());
PortInputFuture { PortInputFuture {
pin: &self.get_mut().pin, pin_port: self.pin.pin.pin_port(),
polarity: PortInputPolarity::Low, phantom: PhantomData,
} }
} }
} }
impl<T> Deref for GpiotePin<T> { pub struct PortInputFuture<'a> {
type Target = GpioPin<Input<T>>; pin_port: u8,
fn deref(&self) -> &Self::Target { phantom: PhantomData<&'a mut AnyPin>,
&self.pin
}
} }
enum PortInputPolarity { impl<'a> Drop for PortInputFuture<'a> {
High,
Low,
}
pub struct PortInputFuture<'a, T> {
pin: &'a GpioPin<Input<T>>,
polarity: PortInputPolarity,
}
impl<'a, T> Drop for PortInputFuture<'a, T> {
fn drop(&mut self) { fn drop(&mut self) {
pin_conf(&self.pin).modify(|_, w| w.sense().disabled()); unsafe { AnyPin::steal(self.pin_port) }
PORT_SIGNALS[pin_num(&self.pin)].reset(); .conf()
.modify(|_, w| w.sense().disabled());
} }
} }
impl<'a, T> Future for PortInputFuture<'a, T> { impl<'a> Future for PortInputFuture<'a> {
type Output = (); type Output = ();
fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
pin_conf(&self.pin).modify(|_, w| match self.polarity { let dis = unsafe { AnyPin::steal(self.pin_port) }
PortInputPolarity::Low => w.sense().low(), .conf()
PortInputPolarity::High => w.sense().high(), .read()
}); .sense()
PORT_SIGNALS[pin_num(&self.pin)].poll_wait(cx) .is_disabled();
if dis {
return Poll::Ready(());
}
PORT_WAKERS[self.pin_port as usize].register(cx.waker());
Poll::Pending
} }
} }