1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
use core::fmt::Debug;
use core::marker::PhantomData;
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
use esp_idf_sys::*;
use enumset::EnumSetType;
use crate::gpio::InputPin;
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum PcntChannel {
Channel0,
Channel1,
}
impl From<PcntChannel> for pcnt_channel_t {
fn from(value: PcntChannel) -> Self {
match value {
PcntChannel::Channel0 => pcnt_channel_t_PCNT_CHANNEL_0,
PcntChannel::Channel1 => pcnt_channel_t_PCNT_CHANNEL_1,
}
}
}
/// PCNT channel action on signal edge
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
pub enum PcntCountMode {
/// Hold current count value
Hold,
/// Increase count value
#[default]
Increment,
/// Decrease count value
Decrement,
}
impl From<PcntCountMode> for pcnt_count_mode_t {
fn from(value: PcntCountMode) -> Self {
match value {
PcntCountMode::Hold => pcnt_channel_edge_action_t_PCNT_CHANNEL_EDGE_ACTION_HOLD,
PcntCountMode::Increment => {
pcnt_channel_edge_action_t_PCNT_CHANNEL_EDGE_ACTION_INCREASE
}
PcntCountMode::Decrement => {
pcnt_channel_edge_action_t_PCNT_CHANNEL_EDGE_ACTION_DECREASE
}
}
}
}
/// PCNT channel action on control level
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
pub enum PcntControlMode {
/// Keep current count mode
Keep,
/// Invert current count mode (increase -> decrease, decrease -> increase)
#[default]
Reverse,
/// Hold current count value
Disable,
}
impl From<PcntControlMode> for pcnt_ctrl_mode_t {
fn from(value: PcntControlMode) -> Self {
match value {
PcntControlMode::Keep => pcnt_channel_level_action_t_PCNT_CHANNEL_LEVEL_ACTION_KEEP,
PcntControlMode::Reverse => {
pcnt_channel_level_action_t_PCNT_CHANNEL_LEVEL_ACTION_INVERSE
}
PcntControlMode::Disable => pcnt_channel_level_action_t_PCNT_CHANNEL_LEVEL_ACTION_HOLD,
}
}
}
#[derive(Debug, EnumSetType)]
#[enumset(repr = "u32")]
pub enum PcntEvent {
/// PCNT watch point event: threshold1 value event
Threshold1 = 2, // pcnt_evt_type_t_PCNT_EVT_THRES_1 = 0x04,
/// PCNT watch point event: threshold0 value event
Threshold0 = 3, // pcnt_evt_type_t_PCNT_EVT_THRES_0 = 0x08,
/// PCNT watch point event: Minimum counter value
LowLimit = 4, // pcnt_evt_type_t_PCNT_EVT_L_LIM = 0x10,
/// PCNT watch point event: Maximum counter value
HighLimit = 5, // pcnt_evt_type_t_PCNT_EVT_H_LIM = 0x20,
/// PCNT watch point event: counter value zero event
Zero = 6, // pcnt_evt_type_t_PCNT_EVT_ZERO = 0x40,
}
pub type PcntEventType = enumset::EnumSet<PcntEvent>;
/// Pulse Counter configuration for a single channel
#[derive(Debug, Copy, Clone, Default)]
pub struct PcntChannelConfig {
/// PCNT low control mode
pub lctrl_mode: PcntControlMode,
/// PCNT high control mode
pub hctrl_mode: PcntControlMode,
/// PCNT positive edge count mode
pub pos_mode: PcntCountMode,
/// PCNT negative edge count mode
pub neg_mode: PcntCountMode,
/// Maximum counter value
pub counter_h_lim: i16,
/// Minimum counter value
pub counter_l_lim: i16,
}
impl PcntChannelConfig {
pub fn new() -> Self {
Default::default()
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum PinIndex {
Pin0 = 0,
Pin1 = 1,
Pin2 = 2,
Pin3 = 3,
}
pub struct PcntDriver<'d> {
unit: pcnt_unit_t,
pins: [i32; 4],
_p: PhantomData<&'d mut ()>,
}
macro_rules! pin_to_number {
($pin:ident) => {
match $pin {
Some(pin) => pin.pin() as _,
None => PCNT_PIN_NOT_USED,
}
};
}
impl<'d> PcntDriver<'d> {
pub fn new<PCNT: Pcnt + 'd>(
_pcnt: PCNT,
pin0: Option<impl InputPin + 'd>,
pin1: Option<impl InputPin + 'd>,
pin2: Option<impl InputPin + 'd>,
pin3: Option<impl InputPin + 'd>,
) -> Result<Self, EspError> {
// consume the pins and keep only the pin number.
let pins = [
pin_to_number!(pin0),
pin_to_number!(pin1),
pin_to_number!(pin2),
pin_to_number!(pin3),
];
Ok(Self {
unit: PCNT::unit(),
pins,
_p: PhantomData,
})
}
/// Configure Pulse Counter chanel
/// @note
/// This function will disable three events: PCNT_EVT_L_LIM, PCNT_EVT_H_LIM, PCNT_EVT_ZERO.
///
/// @param channel Channel to configure
/// @param pulse_pin Pulse signal input pin
/// @param ctrl_pin Control signal input pin
/// @param pconfig Reference of PcntConfig
///
/// @note Set the signal input to PCNT_PIN_NOT_USED if unused.
///
/// returns
/// - ()
/// - EspError
pub fn channel_config(
&mut self,
channel: PcntChannel,
pulse_pin: PinIndex,
ctrl_pin: PinIndex,
pconfig: &PcntChannelConfig,
) -> Result<(), EspError> {
let config = pcnt_config_t {
pulse_gpio_num: self.pins[pulse_pin as usize],
ctrl_gpio_num: self.pins[ctrl_pin as usize],
lctrl_mode: pconfig.lctrl_mode.into(),
hctrl_mode: pconfig.hctrl_mode.into(),
pos_mode: pconfig.pos_mode.into(),
neg_mode: pconfig.neg_mode.into(),
counter_h_lim: pconfig.counter_h_lim,
counter_l_lim: pconfig.counter_l_lim,
channel: channel.into(),
unit: self.unit,
};
unsafe { esp!(pcnt_unit_config(&config as *const pcnt_config_t)) }
}
/// Get pulse counter value
///
/// returns
/// - i16
/// - EspError
pub fn get_counter_value(&self) -> Result<i16, EspError> {
let mut value = 0i16;
unsafe {
esp!(pcnt_get_counter_value(self.unit, &mut value as *mut i16))?;
}
Ok(value)
}
/// Pause PCNT counter of PCNT unit
///
/// returns
/// - ()
/// - EspError
pub fn counter_pause(&self) -> Result<(), EspError> {
unsafe { esp!(pcnt_counter_pause(self.unit)) }
}
/// Resume counting for PCNT counter
///
/// returns
/// - ()
/// - EspError
pub fn counter_resume(&self) -> Result<(), EspError> {
unsafe { esp!(pcnt_counter_resume(self.unit)) }
}
/// Clear and reset PCNT counter value to zero
///
/// returns
/// - ()
/// - EspError
pub fn counter_clear(&self) -> Result<(), EspError> {
unsafe { esp!(pcnt_counter_clear(self.unit)) }
}
/// Enable PCNT interrupt for PCNT unit
/// @note
/// Each Pulse counter unit has five watch point events that share the same interrupt.
/// Configure events with pcnt_event_enable() and pcnt_event_disable()
///
/// returns
/// - ()
/// - EspError
pub fn intr_enable(&self) -> Result<(), EspError> {
unsafe { esp!(pcnt_intr_enable(self.unit)) }
}
/// Disable PCNT interrupt for PCNT unit
///
/// returns
/// - ()
/// - EspError
pub fn intr_disable(&self) -> Result<(), EspError> {
unsafe { esp!(pcnt_intr_disable(self.unit)) }
}
/// Enable PCNT event of PCNT unit
///
/// @param evt_type Watch point event type.
/// All enabled events share the same interrupt (one interrupt per pulse counter unit).
/// returns
/// - ()
/// - EspError
pub fn event_enable(&self, evt_type: PcntEvent) -> Result<(), EspError> {
let evt_type: pcnt_evt_type_t = PcntEventType::only(evt_type).as_repr();
unsafe { esp!(pcnt_event_enable(self.unit, evt_type)) }
}
/// Disable PCNT event of PCNT unit
///
/// @param evt_type Watch point event type.
/// All enabled events share the same interrupt (one interrupt per pulse counter unit).
/// returns
/// - ()
/// - EspError
pub fn event_disable(&self, evt_type: PcntEvent) -> Result<(), EspError> {
let evt_type: pcnt_evt_type_t = PcntEventType::only(evt_type).as_repr();
unsafe { esp!(pcnt_event_disable(self.unit, evt_type)) }
}
fn only_one_event_type(evt_type: PcntEventType) -> Result<pcnt_evt_type_t, EspError> {
match evt_type.iter().count() {
1 => Ok(evt_type.as_repr()),
_ => Err(EspError::from(ESP_ERR_INVALID_ARG as esp_err_t).unwrap()),
}
}
/// Set PCNT event value of PCNT unit
///
/// @param evt_type Watch point event type.
/// All enabled events share the same interrupt (one interrupt per pulse counter unit).
///
/// returns
/// - ()
/// - EspError
pub fn set_event_value(&self, evt_type: PcntEventType, value: i16) -> Result<(), EspError> {
let evt_type = Self::only_one_event_type(evt_type)?;
unsafe { esp!(pcnt_set_event_value(self.unit, evt_type, value)) }
}
/// Get PCNT event value of PCNT unit
///
/// @param evt_type Watch point event type.
/// All enabled events share the same interrupt (one interrupt per pulse counter unit).
///
/// returns
/// - i16
/// - EspError
pub fn get_event_value(&self, evt_type: PcntEventType) -> Result<i16, EspError> {
let evt_type = Self::only_one_event_type(evt_type)?;
let mut value = 0i16;
unsafe {
esp!(pcnt_get_event_value(
self.unit,
evt_type,
&mut value as *mut i16
))?;
}
Ok(value)
}
/// Get PCNT event status of PCNT unit
///
/// returns
/// - i32
/// - EspError
// TODO: status is a bit field!
pub fn get_event_status(&self) -> Result<u32, EspError> {
let mut value = 0u32;
unsafe {
esp!(pcnt_get_event_status(self.unit, &mut value as *mut u32))?;
}
Ok(value)
}
// TODO: not implementing until we can do it safely! Will need to reconfigure channels?
//
// /// Configure PCNT pulse signal input pin and control input pin
// ///
// /// @param channel PcntChannel
// /// @param pulse_io Pulse signal input pin
// /// @param ctrl_io Control signal input pin
// ///
// /// @note Set the signal input to PCNT_PIN_NOT_USED if unused.
// ///
// /// returns
// /// - ()
// /// - EspError
// pub fn set_pin<'a>(
// &mut self,
// channel: PcntChannel,
// pulse_pin: Option<impl InputPin + 'a>,
// ctrl_pin: Option<impl InputPin + 'a>,
// ) -> Result<(), EspError> {
// }
/// Enable PCNT input filter
///
/// returns
/// - ()
/// - EspError
pub fn filter_enable(&self) -> Result<(), EspError> {
unsafe { esp!(pcnt_filter_enable(self.unit)) }
}
/// Disable PCNT input filter
///
/// returns
/// - ()
/// - EspError
pub fn filter_disable(&self) -> Result<(), EspError> {
unsafe { esp!(pcnt_filter_disable(self.unit)) }
}
/// Set PCNT filter value
///
/// @param filter_val PCNT signal filter value, counter in APB_CLK cycles.
/// Any pulses lasting shorter than this will be ignored when the filter is enabled.
/// @note
/// filter_val is a 10-bit value, so the maximum filter_val should be limited to 1023.
///
/// returns
/// - ()
/// - EspError
pub fn set_filter_value(&self, value: u16) -> Result<(), EspError> {
unsafe { esp!(pcnt_set_filter_value(self.unit, value)) }
}
/// Get PCNT filter value
///
/// returns
/// - i16
/// - EspError
pub fn get_filter_value(&self) -> Result<u16, EspError> {
let mut value = 0u16;
unsafe {
esp!(pcnt_get_filter_value(self.unit, &mut value as *mut u16))?;
}
Ok(value)
}
/// Set PCNT counter mode
///
/// @param channel PCNT channel number
/// @param pos_mode Counter mode when detecting positive edge
/// @param neg_mode Counter mode when detecting negative edge
/// @param hctrl_mode Counter mode when control signal is high level
/// @param lctrl_mode Counter mode when control signal is low level
///
/// returns
/// - ()
/// - EspError
pub fn set_mode(
&self,
channel: PcntChannel,
pos_mode: PcntCountMode,
neg_mode: PcntCountMode,
hctrl_mode: PcntControlMode,
lctrl_mode: PcntControlMode,
) -> Result<(), EspError> {
unsafe {
esp!(pcnt_set_mode(
self.unit,
channel.into(),
pos_mode.into(),
neg_mode.into(),
hctrl_mode.into(),
lctrl_mode.into()
))
}
}
/// Add ISR handler for specified unit.
///
/// This ISR handler will be called from an ISR. So there is a stack
/// size limit (configurable as \"ISR stack size\" in menuconfig). This
/// limit is smaller compared to a global PCNT interrupt handler due
/// to the additional level of indirection.
///
/// # Safety
///
/// Care should be taken not to call STD, libc or FreeRTOS APIs (except for a few allowed ones)
/// in the callback passed to this function, as it is executed in an ISR context.
///
/// @param callback Interrupt handler function.
///
/// returns
/// - ()
/// - EspError
#[cfg(feature = "alloc")]
pub unsafe fn subscribe<F>(&self, callback: F) -> Result<(), EspError>
where
F: FnMut(u32) + Send + 'static,
{
self.internal_subscribe(callback)
}
/// Add ISR handler for specified unit.
///
/// This ISR handler will be called from an ISR. So there is a stack
/// size limit (configurable as \"ISR stack size\" in menuconfig). This
/// limit is smaller compared to a global PCNT interrupt handler due
/// to the additional level of indirection.
///
/// # Safety
///
/// Care should be taken not to call STD, libc or FreeRTOS APIs (except for a few allowed ones)
/// in the callback passed to this function, as it is executed in an ISR context.
///
/// Additionally, this method - in contrast to method `subscribe` - allows
/// the passed-in callback/closure to be non-`'static`. This enables users to borrow
/// - in the closure - variables that live on the stack - or more generally - in the same
/// scope where the driver is created.
///
/// HOWEVER: care should be taken NOT to call `core::mem::forget()` on the driver,
/// as that would immediately lead to an UB (crash).
/// Also note that forgetting the driver might happen with `Rc` and `Arc`
/// when circular references are introduced: https://github.com/rust-lang/rust/issues/24456
///
/// The reason is that the closure is actually sent and owned by an ISR routine,
/// which means that if the driver is forgotten, Rust is free to e.g. unwind the stack
/// and the ISR routine will end up with references to variables that no longer exist.
///
/// The destructor of the driver takes care - prior to the driver being dropped and e.g.
/// the stack being unwind - to unsubscribe the ISR routine.
/// Unfortunately, when the driver is forgotten, the un-subscription does not happen
/// and invalid references are left dangling.
///
/// This "local borrowing" will only be possible to express in a safe way once/if `!Leak` types
/// are introduced to Rust (i.e. the impossibility to "forget" a type and thus not call its destructor).
///
/// @param callback Interrupt handler function.
///
/// returns
/// - ()
/// - EspError
#[cfg(feature = "alloc")]
pub unsafe fn subscribe_nonstatic<F>(&self, callback: F) -> Result<(), EspError>
where
F: FnMut(u32) + Send + 'd,
{
self.internal_subscribe(callback)
}
#[cfg(feature = "alloc")]
fn internal_subscribe<F>(&self, callback: F) -> Result<(), EspError>
where
F: FnMut(u32) + Send + 'd,
{
enable_isr_service()?;
self.unsubscribe()?;
let callback: alloc::boxed::Box<dyn FnMut(u32) + 'd> = alloc::boxed::Box::new(callback);
unsafe {
ISR_HANDLERS[self.unit as usize] = Some(core::mem::transmute::<
alloc::boxed::Box<dyn FnMut(u32)>,
alloc::boxed::Box<dyn FnMut(u32)>,
>(callback));
}
esp!(unsafe {
pcnt_isr_handler_add(
self.unit,
Some(Self::handle_isr),
self.unit as *mut core::ffi::c_void,
)
})?;
Ok(())
}
/// Remove ISR handler for specified unit.
///
/// returns
/// - ()
/// - EspError
#[cfg(feature = "alloc")]
pub fn unsubscribe(&self) -> Result<(), EspError> {
unsafe {
esp!(pcnt_isr_handler_remove(self.unit))?;
ISR_HANDLERS[self.unit as usize] = None;
}
Ok(())
}
#[cfg(feature = "alloc")]
unsafe extern "C" fn handle_isr(data: *mut core::ffi::c_void) {
let unit = data as pcnt_unit_t;
if let Some(f) = &mut ISR_HANDLERS[unit as usize] {
let mut value = 0u32;
esp!(pcnt_get_event_status(unit, &mut value as *mut u32))
.expect("failed to fetch event status!");
f(value);
}
}
}
impl Drop for PcntDriver<'_> {
fn drop(&mut self) {
let _ = self.counter_pause();
let _ = self.intr_disable();
#[cfg(feature = "alloc")]
unsafe {
pcnt_isr_handler_remove(self.unit);
ISR_HANDLERS[self.unit as usize] = None
};
}
}
static ISR_ALLOC_FLAGS: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
#[cfg(feature = "alloc")]
static ISR_SERVICE_ENABLED: core::sync::atomic::AtomicBool =
core::sync::atomic::AtomicBool::new(false);
#[cfg(feature = "alloc")]
static PCNT_CS: crate::task::CriticalSection = crate::task::CriticalSection::new();
pub fn init_isr_alloc_flags(flags: enumset::EnumSet<crate::interrupt::InterruptType>) {
ISR_ALLOC_FLAGS.store(
crate::interrupt::InterruptType::to_native(flags),
core::sync::atomic::Ordering::SeqCst,
);
}
#[cfg(feature = "alloc")]
fn enable_isr_service() -> Result<(), EspError> {
use core::sync::atomic::Ordering;
if !ISR_SERVICE_ENABLED.load(Ordering::SeqCst) {
let _cs = PCNT_CS.enter();
if !ISR_SERVICE_ENABLED.load(Ordering::SeqCst) {
esp!(unsafe { pcnt_isr_service_install(ISR_ALLOC_FLAGS.load(Ordering::SeqCst) as _) })?;
ISR_SERVICE_ENABLED.store(true, Ordering::SeqCst);
}
}
Ok(())
}
#[cfg(feature = "alloc")]
type IsrHandler = Option<Box<dyn FnMut(u32)>>;
#[cfg(feature = "alloc")]
static mut ISR_HANDLERS: [IsrHandler; pcnt_unit_t_PCNT_UNIT_MAX as usize] = [
None,
None,
None,
None,
#[cfg(esp32)]
None,
#[cfg(esp32)]
None,
#[cfg(esp32)]
None,
#[cfg(esp32)]
None,
];
pub trait Pcnt {
fn unit() -> pcnt_unit_t;
}
macro_rules! impl_pcnt {
($pcnt:ident: $unit:expr) => {
crate::impl_peripheral!($pcnt);
impl Pcnt for $pcnt<'_> {
#[inline(always)]
fn unit() -> pcnt_unit_t {
$unit
}
}
};
}
impl_pcnt!(PCNT0: pcnt_unit_t_PCNT_UNIT_0);
impl_pcnt!(PCNT1: pcnt_unit_t_PCNT_UNIT_1);
impl_pcnt!(PCNT2: pcnt_unit_t_PCNT_UNIT_2);
impl_pcnt!(PCNT3: pcnt_unit_t_PCNT_UNIT_3);
#[cfg(esp32)]
impl_pcnt!(PCNT4: pcnt_unit_t_PCNT_UNIT_4);
#[cfg(esp32)]
impl_pcnt!(PCNT5: pcnt_unit_t_PCNT_UNIT_5);
#[cfg(esp32)]
impl_pcnt!(PCNT6: pcnt_unit_t_PCNT_UNIT_6);
#[cfg(esp32)]
impl_pcnt!(PCNT7: pcnt_unit_t_PCNT_UNIT_7);