1use core::convert::Infallible;
4use core::future::{poll_fn, Future};
5use core::task::{Context, Poll};
6
7use embassy_hal_internal::{impl_peripheral, Peri, PeripheralType};
8use embassy_sync::waitqueue::AtomicWaker;
9
10use crate::gpio::{AnyPin, Flex, Input, Output, Pin as GpioPin, SealedPin as _};
11use crate::interrupt::InterruptExt;
12#[cfg(not(feature = "_nrf51"))]
13use crate::pac::gpio::vals::Detectmode;
14use crate::pac::gpio::vals::Sense;
15use crate::pac::gpiote::vals::{Mode, Outinit, Polarity};
16use crate::ppi::{Event, Task};
17use crate::{interrupt, pac, peripherals};
18
19#[cfg(feature = "_nrf51")]
20const CHANNEL_COUNT: usize = 4;
22#[cfg(not(feature = "_nrf51"))]
23const CHANNEL_COUNT: usize = 8;
25
26#[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))]
27const PIN_COUNT: usize = 48;
28#[cfg(not(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340")))]
29const PIN_COUNT: usize = 32;
30
31#[allow(clippy::declare_interior_mutable_const)]
32static CHANNEL_WAKERS: [AtomicWaker; CHANNEL_COUNT] = [const { AtomicWaker::new() }; CHANNEL_COUNT];
33static PORT_WAKERS: [AtomicWaker; PIN_COUNT] = [const { AtomicWaker::new() }; PIN_COUNT];
34
35pub enum InputChannelPolarity {
37 None,
39 HiToLo,
41 LoToHi,
43 Toggle,
45}
46
47pub enum OutputChannelPolarity {
49 Set,
51 Clear,
53 Toggle,
55}
56
57fn regs() -> pac::gpiote::Gpiote {
58 cfg_if::cfg_if! {
59 if #[cfg(any(feature="nrf5340-app-s", feature="nrf9160-s", feature="nrf9120-s"))] {
60 pac::GPIOTE0
61 } else if #[cfg(any(feature="nrf5340-app-ns", feature="nrf9160-ns", feature="nrf9120-ns"))] {
62 pac::GPIOTE1
63 } else {
64 pac::GPIOTE
65 }
66 }
67}
68
69pub(crate) fn init(irq_prio: crate::interrupt::Priority) {
70 #[cfg(not(feature = "_nrf51"))]
72 {
73 #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))]
74 let ports = &[pac::P0, pac::P1];
75 #[cfg(not(any(feature = "_nrf51", feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340")))]
76 let ports = &[pac::P0];
77
78 for &p in ports {
79 p.detectmode().write(|w| w.set_detectmode(Detectmode::LDETECT));
81 p.latch().write(|w| w.0 = 0xFFFFFFFF)
83 }
84 }
85
86 #[cfg(any(feature = "nrf5340-app-s", feature = "nrf9160-s", feature = "nrf9120-s"))]
88 let irq = interrupt::GPIOTE0;
89 #[cfg(any(feature = "nrf5340-app-ns", feature = "nrf9160-ns", feature = "nrf9120-ns"))]
90 let irq = interrupt::GPIOTE1;
91 #[cfg(any(feature = "_nrf51", feature = "_nrf52", feature = "nrf5340-net"))]
92 let irq = interrupt::GPIOTE;
93
94 irq.unpend();
95 irq.set_priority(irq_prio);
96 unsafe { irq.enable() };
97
98 let g = regs();
99 g.intenset().write(|w| w.set_port(true));
100}
101
102#[cfg(any(feature = "nrf5340-app-s", feature = "nrf9160-s", feature = "nrf9120-s"))]
103#[cfg(feature = "rt")]
104#[interrupt]
105fn GPIOTE0() {
106 unsafe { handle_gpiote_interrupt() };
107}
108
109#[cfg(any(feature = "nrf5340-app-ns", feature = "nrf9160-ns", feature = "nrf9120-ns"))]
110#[cfg(feature = "rt")]
111#[interrupt]
112fn GPIOTE1() {
113 unsafe { handle_gpiote_interrupt() };
114}
115
116#[cfg(any(feature = "_nrf51", feature = "_nrf52", feature = "nrf5340-net"))]
117#[cfg(feature = "rt")]
118#[interrupt]
119fn GPIOTE() {
120 unsafe { handle_gpiote_interrupt() };
121}
122
123unsafe fn handle_gpiote_interrupt() {
124 let g = regs();
125
126 for i in 0..CHANNEL_COUNT {
127 if g.events_in(i).read() != 0 {
128 g.intenclr().write(|w| w.0 = 1 << i);
129 CHANNEL_WAKERS[i].wake();
130 }
131 }
132
133 if g.events_port().read() != 0 {
134 g.events_port().write_value(0);
135
136 #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))]
137 let ports = &[pac::P0, pac::P1];
138 #[cfg(not(any(feature = "_nrf51", feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340")))]
139 let ports = &[pac::P0];
140 #[cfg(feature = "_nrf51")]
141 let ports = &[pac::GPIO];
142
143 #[cfg(feature = "_nrf51")]
144 for (port, &p) in ports.iter().enumerate() {
145 let inp = p.in_().read();
146 for pin in 0..32 {
147 let fired = match p.pin_cnf(pin as usize).read().sense() {
148 Sense::HIGH => inp.pin(pin),
149 Sense::LOW => !inp.pin(pin),
150 _ => false,
151 };
152
153 if fired {
154 PORT_WAKERS[port * 32 + pin as usize].wake();
155 p.pin_cnf(pin as usize).modify(|w| w.set_sense(Sense::DISABLED));
156 }
157 }
158 }
159
160 #[cfg(not(feature = "_nrf51"))]
161 for (port, &p) in ports.iter().enumerate() {
162 let bits = p.latch().read().0;
163 for pin in BitIter(bits) {
164 p.pin_cnf(pin as usize).modify(|w| w.set_sense(Sense::DISABLED));
165 PORT_WAKERS[port * 32 + pin as usize].wake();
166 }
167 p.latch().write(|w| w.0 = bits);
168 }
169 }
170}
171
172#[cfg(not(feature = "_nrf51"))]
173struct BitIter(u32);
174
175#[cfg(not(feature = "_nrf51"))]
176impl Iterator for BitIter {
177 type Item = u32;
178
179 fn next(&mut self) -> Option<Self::Item> {
180 match self.0.trailing_zeros() {
181 32 => None,
182 b => {
183 self.0 &= !(1 << b);
184 Some(b)
185 }
186 }
187 }
188}
189
190pub struct InputChannel<'d> {
192 ch: Peri<'d, AnyChannel>,
193 pin: Input<'d>,
194}
195
196impl InputChannel<'static> {
197 pub fn persist(self) {
201 core::mem::forget(self);
202 }
203}
204
205impl<'d> Drop for InputChannel<'d> {
206 fn drop(&mut self) {
207 let g = regs();
208 let num = self.ch.number();
209 g.config(num).write(|w| w.set_mode(Mode::DISABLED));
210 g.intenclr().write(|w| w.0 = 1 << num);
211 }
212}
213
214impl<'d> InputChannel<'d> {
215 pub fn new(ch: Peri<'d, impl Channel>, pin: Input<'d>, polarity: InputChannelPolarity) -> Self {
217 let g = regs();
218 let num = ch.number();
219
220 g.config(num).write(|w| {
221 w.set_mode(Mode::EVENT);
222 match polarity {
223 InputChannelPolarity::HiToLo => w.set_polarity(Polarity::HI_TO_LO),
224 InputChannelPolarity::LoToHi => w.set_polarity(Polarity::LO_TO_HI),
225 InputChannelPolarity::None => w.set_polarity(Polarity::NONE),
226 InputChannelPolarity::Toggle => w.set_polarity(Polarity::TOGGLE),
227 };
228 #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))]
229 w.set_port(match pin.pin.pin.port() {
230 crate::gpio::Port::Port0 => false,
231 crate::gpio::Port::Port1 => true,
232 });
233 w.set_psel(pin.pin.pin.pin());
234 });
235
236 g.events_in(num).write_value(0);
237
238 InputChannel { ch: ch.into(), pin }
239 }
240
241 pub async fn wait(&self) {
243 let g = regs();
244 let num = self.ch.number();
245
246 g.events_in(num).write_value(0);
248 g.intenset().write(|w| w.0 = 1 << num);
249
250 poll_fn(|cx| {
251 CHANNEL_WAKERS[num].register(cx.waker());
252
253 if g.events_in(num).read() != 0 {
254 Poll::Ready(())
255 } else {
256 Poll::Pending
257 }
258 })
259 .await;
260 }
261
262 pub fn event_in(&self) -> Event<'d> {
264 let g = regs();
265 Event::from_reg(g.events_in(self.ch.number()))
266 }
267}
268
269pub struct OutputChannel<'d> {
271 ch: Peri<'d, AnyChannel>,
272 _pin: Output<'d>,
273}
274
275impl OutputChannel<'static> {
276 pub fn persist(self) {
280 core::mem::forget(self);
281 }
282}
283
284impl<'d> Drop for OutputChannel<'d> {
285 fn drop(&mut self) {
286 let g = regs();
287 let num = self.ch.number();
288 g.config(num).write(|w| w.set_mode(Mode::DISABLED));
289 g.intenclr().write(|w| w.0 = 1 << num);
290 }
291}
292
293impl<'d> OutputChannel<'d> {
294 pub fn new(ch: Peri<'d, impl Channel>, pin: Output<'d>, polarity: OutputChannelPolarity) -> Self {
296 let g = regs();
297 let num = ch.number();
298
299 g.config(num).write(|w| {
300 w.set_mode(Mode::TASK);
301 match pin.is_set_high() {
302 true => w.set_outinit(Outinit::HIGH),
303 false => w.set_outinit(Outinit::LOW),
304 };
305 match polarity {
306 OutputChannelPolarity::Set => w.set_polarity(Polarity::HI_TO_LO),
307 OutputChannelPolarity::Clear => w.set_polarity(Polarity::LO_TO_HI),
308 OutputChannelPolarity::Toggle => w.set_polarity(Polarity::TOGGLE),
309 };
310 #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))]
311 w.set_port(match pin.pin.pin.port() {
312 crate::gpio::Port::Port0 => false,
313 crate::gpio::Port::Port1 => true,
314 });
315 w.set_psel(pin.pin.pin.pin());
316 });
317
318 OutputChannel {
319 ch: ch.into(),
320 _pin: pin,
321 }
322 }
323
324 pub fn out(&self) {
326 let g = regs();
327 g.tasks_out(self.ch.number()).write_value(1);
328 }
329
330 #[cfg(not(feature = "_nrf51"))]
332 pub fn set(&self) {
333 let g = regs();
334 g.tasks_set(self.ch.number()).write_value(1);
335 }
336
337 #[cfg(not(feature = "_nrf51"))]
339 pub fn clear(&self) {
340 let g = regs();
341 g.tasks_clr(self.ch.number()).write_value(1);
342 }
343
344 pub fn task_out(&self) -> Task<'d> {
346 let g = regs();
347 Task::from_reg(g.tasks_out(self.ch.number()))
348 }
349
350 #[cfg(not(feature = "_nrf51"))]
352 pub fn task_clr(&self) -> Task<'d> {
353 let g = regs();
354 Task::from_reg(g.tasks_clr(self.ch.number()))
355 }
356
357 #[cfg(not(feature = "_nrf51"))]
359 pub fn task_set(&self) -> Task<'d> {
360 let g = regs();
361 Task::from_reg(g.tasks_set(self.ch.number()))
362 }
363}
364
365#[must_use = "futures do nothing unless you `.await` or poll them"]
368pub(crate) struct PortInputFuture<'a> {
369 pin: Peri<'a, AnyPin>,
370}
371
372impl<'a> PortInputFuture<'a> {
373 fn new(pin: Peri<'a, impl GpioPin>) -> Self {
374 Self { pin: pin.into() }
375 }
376}
377
378impl<'a> Unpin for PortInputFuture<'a> {}
379
380impl<'a> Drop for PortInputFuture<'a> {
381 fn drop(&mut self) {
382 self.pin.conf().modify(|w| w.set_sense(Sense::DISABLED));
383 }
384}
385
386impl<'a> Future for PortInputFuture<'a> {
387 type Output = ();
388
389 fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
390 PORT_WAKERS[self.pin.pin_port() as usize].register(cx.waker());
391
392 if self.pin.conf().read().sense() == Sense::DISABLED {
393 Poll::Ready(())
394 } else {
395 Poll::Pending
396 }
397 }
398}
399
400impl<'d> Input<'d> {
401 pub async fn wait_for_high(&mut self) {
403 self.pin.wait_for_high().await
404 }
405
406 pub async fn wait_for_low(&mut self) {
408 self.pin.wait_for_low().await
409 }
410
411 pub async fn wait_for_rising_edge(&mut self) {
413 self.pin.wait_for_rising_edge().await
414 }
415
416 pub async fn wait_for_falling_edge(&mut self) {
418 self.pin.wait_for_falling_edge().await
419 }
420
421 pub async fn wait_for_any_edge(&mut self) {
423 self.pin.wait_for_any_edge().await
424 }
425}
426
427impl<'d> Flex<'d> {
428 pub async fn wait_for_high(&mut self) {
430 self.pin.conf().modify(|w| w.set_sense(Sense::HIGH));
431 PortInputFuture::new(self.pin.reborrow()).await
432 }
433
434 pub async fn wait_for_low(&mut self) {
436 self.pin.conf().modify(|w| w.set_sense(Sense::LOW));
437 PortInputFuture::new(self.pin.reborrow()).await
438 }
439
440 pub async fn wait_for_rising_edge(&mut self) {
442 self.wait_for_low().await;
443 self.wait_for_high().await;
444 }
445
446 pub async fn wait_for_falling_edge(&mut self) {
448 self.wait_for_high().await;
449 self.wait_for_low().await;
450 }
451
452 pub async fn wait_for_any_edge(&mut self) {
454 if self.is_high() {
455 self.pin.conf().modify(|w| w.set_sense(Sense::LOW));
456 } else {
457 self.pin.conf().modify(|w| w.set_sense(Sense::HIGH));
458 }
459 PortInputFuture::new(self.pin.reborrow()).await
460 }
461}
462
463trait SealedChannel {}
466
467#[allow(private_bounds)]
471pub trait Channel: PeripheralType + SealedChannel + Into<AnyChannel> + Sized + 'static {
472 fn number(&self) -> usize;
474}
475
476pub struct AnyChannel {
483 number: u8,
484}
485impl_peripheral!(AnyChannel);
486impl SealedChannel for AnyChannel {}
487impl Channel for AnyChannel {
488 fn number(&self) -> usize {
489 self.number as usize
490 }
491}
492
493macro_rules! impl_channel {
494 ($type:ident, $number:expr) => {
495 impl SealedChannel for peripherals::$type {}
496 impl Channel for peripherals::$type {
497 fn number(&self) -> usize {
498 $number as usize
499 }
500 }
501
502 impl From<peripherals::$type> for AnyChannel {
503 fn from(val: peripherals::$type) -> Self {
504 Self {
505 number: val.number() as u8,
506 }
507 }
508 }
509 };
510}
511
512impl_channel!(GPIOTE_CH0, 0);
513impl_channel!(GPIOTE_CH1, 1);
514impl_channel!(GPIOTE_CH2, 2);
515impl_channel!(GPIOTE_CH3, 3);
516#[cfg(not(feature = "_nrf51"))]
517impl_channel!(GPIOTE_CH4, 4);
518#[cfg(not(feature = "_nrf51"))]
519impl_channel!(GPIOTE_CH5, 5);
520#[cfg(not(feature = "_nrf51"))]
521impl_channel!(GPIOTE_CH6, 6);
522#[cfg(not(feature = "_nrf51"))]
523impl_channel!(GPIOTE_CH7, 7);
524
525mod eh02 {
528 use super::*;
529
530 impl<'d> embedded_hal_02::digital::v2::InputPin for InputChannel<'d> {
531 type Error = Infallible;
532
533 fn is_high(&self) -> Result<bool, Self::Error> {
534 Ok(self.pin.is_high())
535 }
536
537 fn is_low(&self) -> Result<bool, Self::Error> {
538 Ok(self.pin.is_low())
539 }
540 }
541}
542
543impl<'d> embedded_hal_1::digital::ErrorType for InputChannel<'d> {
544 type Error = Infallible;
545}
546
547impl<'d> embedded_hal_1::digital::InputPin for InputChannel<'d> {
548 fn is_high(&mut self) -> Result<bool, Self::Error> {
549 Ok(self.pin.is_high())
550 }
551
552 fn is_low(&mut self) -> Result<bool, Self::Error> {
553 Ok(self.pin.is_low())
554 }
555}
556
557impl<'d> embedded_hal_async::digital::Wait for Input<'d> {
558 async fn wait_for_high(&mut self) -> Result<(), Self::Error> {
559 Ok(self.wait_for_high().await)
560 }
561
562 async fn wait_for_low(&mut self) -> Result<(), Self::Error> {
563 Ok(self.wait_for_low().await)
564 }
565
566 async fn wait_for_rising_edge(&mut self) -> Result<(), Self::Error> {
567 Ok(self.wait_for_rising_edge().await)
568 }
569
570 async fn wait_for_falling_edge(&mut self) -> Result<(), Self::Error> {
571 Ok(self.wait_for_falling_edge().await)
572 }
573
574 async fn wait_for_any_edge(&mut self) -> Result<(), Self::Error> {
575 Ok(self.wait_for_any_edge().await)
576 }
577}
578
579impl<'d> embedded_hal_async::digital::Wait for Flex<'d> {
580 async fn wait_for_high(&mut self) -> Result<(), Self::Error> {
581 Ok(self.wait_for_high().await)
582 }
583
584 async fn wait_for_low(&mut self) -> Result<(), Self::Error> {
585 Ok(self.wait_for_low().await)
586 }
587
588 async fn wait_for_rising_edge(&mut self) -> Result<(), Self::Error> {
589 Ok(self.wait_for_rising_edge().await)
590 }
591
592 async fn wait_for_falling_edge(&mut self) -> Result<(), Self::Error> {
593 Ok(self.wait_for_falling_edge().await)
594 }
595
596 async fn wait_for_any_edge(&mut self) -> Result<(), Self::Error> {
597 Ok(self.wait_for_any_edge().await)
598 }
599}