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<'d> Drop for InputChannel<'d> {
197 fn drop(&mut self) {
198 let g = regs();
199 let num = self.ch.number();
200 g.config(num).write(|w| w.set_mode(Mode::DISABLED));
201 g.intenclr().write(|w| w.0 = 1 << num);
202 }
203}
204
205impl<'d> InputChannel<'d> {
206 pub fn new(ch: Peri<'d, impl Channel>, pin: Input<'d>, polarity: InputChannelPolarity) -> Self {
208 let g = regs();
209 let num = ch.number();
210
211 g.config(num).write(|w| {
212 w.set_mode(Mode::EVENT);
213 match polarity {
214 InputChannelPolarity::HiToLo => w.set_polarity(Polarity::HI_TO_LO),
215 InputChannelPolarity::LoToHi => w.set_polarity(Polarity::LO_TO_HI),
216 InputChannelPolarity::None => w.set_polarity(Polarity::NONE),
217 InputChannelPolarity::Toggle => w.set_polarity(Polarity::TOGGLE),
218 };
219 #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))]
220 w.set_port(match pin.pin.pin.port() {
221 crate::gpio::Port::Port0 => false,
222 crate::gpio::Port::Port1 => true,
223 });
224 w.set_psel(pin.pin.pin.pin());
225 });
226
227 g.events_in(num).write_value(0);
228
229 InputChannel { ch: ch.into(), pin }
230 }
231
232 pub async fn wait(&self) {
234 let g = regs();
235 let num = self.ch.number();
236
237 g.events_in(num).write_value(0);
239 g.intenset().write(|w| w.0 = 1 << num);
240
241 poll_fn(|cx| {
242 CHANNEL_WAKERS[num].register(cx.waker());
243
244 if g.events_in(num).read() != 0 {
245 Poll::Ready(())
246 } else {
247 Poll::Pending
248 }
249 })
250 .await;
251 }
252
253 pub fn event_in(&self) -> Event<'d> {
255 let g = regs();
256 Event::from_reg(g.events_in(self.ch.number()))
257 }
258}
259
260pub struct OutputChannel<'d> {
262 ch: Peri<'d, AnyChannel>,
263 _pin: Output<'d>,
264}
265
266impl<'d> Drop for OutputChannel<'d> {
267 fn drop(&mut self) {
268 let g = regs();
269 let num = self.ch.number();
270 g.config(num).write(|w| w.set_mode(Mode::DISABLED));
271 g.intenclr().write(|w| w.0 = 1 << num);
272 }
273}
274
275impl<'d> OutputChannel<'d> {
276 pub fn new(ch: Peri<'d, impl Channel>, pin: Output<'d>, polarity: OutputChannelPolarity) -> Self {
278 let g = regs();
279 let num = ch.number();
280
281 g.config(num).write(|w| {
282 w.set_mode(Mode::TASK);
283 match pin.is_set_high() {
284 true => w.set_outinit(Outinit::HIGH),
285 false => w.set_outinit(Outinit::LOW),
286 };
287 match polarity {
288 OutputChannelPolarity::Set => w.set_polarity(Polarity::HI_TO_LO),
289 OutputChannelPolarity::Clear => w.set_polarity(Polarity::LO_TO_HI),
290 OutputChannelPolarity::Toggle => w.set_polarity(Polarity::TOGGLE),
291 };
292 #[cfg(any(feature = "nrf52833", feature = "nrf52840", feature = "_nrf5340"))]
293 w.set_port(match pin.pin.pin.port() {
294 crate::gpio::Port::Port0 => false,
295 crate::gpio::Port::Port1 => true,
296 });
297 w.set_psel(pin.pin.pin.pin());
298 });
299
300 OutputChannel {
301 ch: ch.into(),
302 _pin: pin,
303 }
304 }
305
306 pub fn out(&self) {
308 let g = regs();
309 g.tasks_out(self.ch.number()).write_value(1);
310 }
311
312 #[cfg(not(feature = "_nrf51"))]
314 pub fn set(&self) {
315 let g = regs();
316 g.tasks_set(self.ch.number()).write_value(1);
317 }
318
319 #[cfg(not(feature = "_nrf51"))]
321 pub fn clear(&self) {
322 let g = regs();
323 g.tasks_clr(self.ch.number()).write_value(1);
324 }
325
326 pub fn task_out(&self) -> Task<'d> {
328 let g = regs();
329 Task::from_reg(g.tasks_out(self.ch.number()))
330 }
331
332 #[cfg(not(feature = "_nrf51"))]
334 pub fn task_clr(&self) -> Task<'d> {
335 let g = regs();
336 Task::from_reg(g.tasks_clr(self.ch.number()))
337 }
338
339 #[cfg(not(feature = "_nrf51"))]
341 pub fn task_set(&self) -> Task<'d> {
342 let g = regs();
343 Task::from_reg(g.tasks_set(self.ch.number()))
344 }
345}
346
347#[must_use = "futures do nothing unless you `.await` or poll them"]
350pub(crate) struct PortInputFuture<'a> {
351 pin: Peri<'a, AnyPin>,
352}
353
354impl<'a> PortInputFuture<'a> {
355 fn new(pin: Peri<'a, impl GpioPin>) -> Self {
356 Self { pin: pin.into() }
357 }
358}
359
360impl<'a> Unpin for PortInputFuture<'a> {}
361
362impl<'a> Drop for PortInputFuture<'a> {
363 fn drop(&mut self) {
364 self.pin.conf().modify(|w| w.set_sense(Sense::DISABLED));
365 }
366}
367
368impl<'a> Future for PortInputFuture<'a> {
369 type Output = ();
370
371 fn poll(self: core::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
372 PORT_WAKERS[self.pin.pin_port() as usize].register(cx.waker());
373
374 if self.pin.conf().read().sense() == Sense::DISABLED {
375 Poll::Ready(())
376 } else {
377 Poll::Pending
378 }
379 }
380}
381
382impl<'d> Input<'d> {
383 pub async fn wait_for_high(&mut self) {
385 self.pin.wait_for_high().await
386 }
387
388 pub async fn wait_for_low(&mut self) {
390 self.pin.wait_for_low().await
391 }
392
393 pub async fn wait_for_rising_edge(&mut self) {
395 self.pin.wait_for_rising_edge().await
396 }
397
398 pub async fn wait_for_falling_edge(&mut self) {
400 self.pin.wait_for_falling_edge().await
401 }
402
403 pub async fn wait_for_any_edge(&mut self) {
405 self.pin.wait_for_any_edge().await
406 }
407}
408
409impl<'d> Flex<'d> {
410 pub async fn wait_for_high(&mut self) {
412 self.pin.conf().modify(|w| w.set_sense(Sense::HIGH));
413 PortInputFuture::new(self.pin.reborrow()).await
414 }
415
416 pub async fn wait_for_low(&mut self) {
418 self.pin.conf().modify(|w| w.set_sense(Sense::LOW));
419 PortInputFuture::new(self.pin.reborrow()).await
420 }
421
422 pub async fn wait_for_rising_edge(&mut self) {
424 self.wait_for_low().await;
425 self.wait_for_high().await;
426 }
427
428 pub async fn wait_for_falling_edge(&mut self) {
430 self.wait_for_high().await;
431 self.wait_for_low().await;
432 }
433
434 pub async fn wait_for_any_edge(&mut self) {
436 if self.is_high() {
437 self.pin.conf().modify(|w| w.set_sense(Sense::LOW));
438 } else {
439 self.pin.conf().modify(|w| w.set_sense(Sense::HIGH));
440 }
441 PortInputFuture::new(self.pin.reborrow()).await
442 }
443}
444
445trait SealedChannel {}
448
449#[allow(private_bounds)]
453pub trait Channel: PeripheralType + SealedChannel + Into<AnyChannel> + Sized + 'static {
454 fn number(&self) -> usize;
456}
457
458pub struct AnyChannel {
465 number: u8,
466}
467impl_peripheral!(AnyChannel);
468impl SealedChannel for AnyChannel {}
469impl Channel for AnyChannel {
470 fn number(&self) -> usize {
471 self.number as usize
472 }
473}
474
475macro_rules! impl_channel {
476 ($type:ident, $number:expr) => {
477 impl SealedChannel for peripherals::$type {}
478 impl Channel for peripherals::$type {
479 fn number(&self) -> usize {
480 $number as usize
481 }
482 }
483
484 impl From<peripherals::$type> for AnyChannel {
485 fn from(val: peripherals::$type) -> Self {
486 Self {
487 number: val.number() as u8,
488 }
489 }
490 }
491 };
492}
493
494impl_channel!(GPIOTE_CH0, 0);
495impl_channel!(GPIOTE_CH1, 1);
496impl_channel!(GPIOTE_CH2, 2);
497impl_channel!(GPIOTE_CH3, 3);
498#[cfg(not(feature = "_nrf51"))]
499impl_channel!(GPIOTE_CH4, 4);
500#[cfg(not(feature = "_nrf51"))]
501impl_channel!(GPIOTE_CH5, 5);
502#[cfg(not(feature = "_nrf51"))]
503impl_channel!(GPIOTE_CH6, 6);
504#[cfg(not(feature = "_nrf51"))]
505impl_channel!(GPIOTE_CH7, 7);
506
507mod eh02 {
510 use super::*;
511
512 impl<'d> embedded_hal_02::digital::v2::InputPin for InputChannel<'d> {
513 type Error = Infallible;
514
515 fn is_high(&self) -> Result<bool, Self::Error> {
516 Ok(self.pin.is_high())
517 }
518
519 fn is_low(&self) -> Result<bool, Self::Error> {
520 Ok(self.pin.is_low())
521 }
522 }
523}
524
525impl<'d> embedded_hal_1::digital::ErrorType for InputChannel<'d> {
526 type Error = Infallible;
527}
528
529impl<'d> embedded_hal_1::digital::InputPin for InputChannel<'d> {
530 fn is_high(&mut self) -> Result<bool, Self::Error> {
531 Ok(self.pin.is_high())
532 }
533
534 fn is_low(&mut self) -> Result<bool, Self::Error> {
535 Ok(self.pin.is_low())
536 }
537}
538
539impl<'d> embedded_hal_async::digital::Wait for Input<'d> {
540 async fn wait_for_high(&mut self) -> Result<(), Self::Error> {
541 Ok(self.wait_for_high().await)
542 }
543
544 async fn wait_for_low(&mut self) -> Result<(), Self::Error> {
545 Ok(self.wait_for_low().await)
546 }
547
548 async fn wait_for_rising_edge(&mut self) -> Result<(), Self::Error> {
549 Ok(self.wait_for_rising_edge().await)
550 }
551
552 async fn wait_for_falling_edge(&mut self) -> Result<(), Self::Error> {
553 Ok(self.wait_for_falling_edge().await)
554 }
555
556 async fn wait_for_any_edge(&mut self) -> Result<(), Self::Error> {
557 Ok(self.wait_for_any_edge().await)
558 }
559}
560
561impl<'d> embedded_hal_async::digital::Wait for Flex<'d> {
562 async fn wait_for_high(&mut self) -> Result<(), Self::Error> {
563 Ok(self.wait_for_high().await)
564 }
565
566 async fn wait_for_low(&mut self) -> Result<(), Self::Error> {
567 Ok(self.wait_for_low().await)
568 }
569
570 async fn wait_for_rising_edge(&mut self) -> Result<(), Self::Error> {
571 Ok(self.wait_for_rising_edge().await)
572 }
573
574 async fn wait_for_falling_edge(&mut self) -> Result<(), Self::Error> {
575 Ok(self.wait_for_falling_edge().await)
576 }
577
578 async fn wait_for_any_edge(&mut self) -> Result<(), Self::Error> {
579 Ok(self.wait_for_any_edge().await)
580 }
581}