Skip to main content

esp_hal/pcnt/
unit.rs

1//! # PCNT - Unit Module
2//!
3//! ## Overview
4//! The `unit` module configures and operates a single pulse-counter unit.
5//! Construct a [`Unit`] from a `PCNTn_UNITm` singleton. Units can be paused,
6//! resumed, and cleared, and can listen for threshold and limit events.
7
8#[cfg(soc_has_clock_node_pcnt_function_clock)]
9use crate::soc::clocks::ClockTree;
10use crate::{
11    interrupt::{InterruptConfigurable, InterruptHandler},
12    pcnt::{AnyPcntUnit, Instance, channel::Channel},
13    system::PeripheralGuard,
14};
15
16/// Invalid filter threshold value
17#[derive(Debug, Clone, Copy, PartialEq)]
18#[cfg_attr(feature = "defmt", derive(defmt::Format))]
19pub struct InvalidFilterThreshold;
20
21/// Invalid low limit - must be < 0.
22#[derive(Debug, Clone, Copy, PartialEq)]
23#[cfg_attr(feature = "defmt", derive(defmt::Format))]
24pub struct InvalidLowLimit;
25
26/// Invalid high limit - must be > 0.
27#[derive(Debug, Clone, Copy, PartialEq)]
28#[cfg_attr(feature = "defmt", derive(defmt::Format))]
29pub struct InvalidHighLimit;
30
31/// the current status of the counter.
32#[derive(Copy, Clone, Debug, Default, PartialEq)]
33#[cfg_attr(feature = "defmt", derive(defmt::Format))]
34pub enum ZeroMode {
35    /// pulse counter decreases from positive to 0.
36    #[default]
37    PosZero  = 0,
38    /// pulse counter increases from negative to 0
39    NegZero  = 1,
40    /// pulse counter is negative (not implemented?)
41    Negative = 2,
42    /// pulse counter is positive (not implemented?)
43    Positive = 3,
44}
45
46impl From<u8> for ZeroMode {
47    fn from(value: u8) -> Self {
48        match value {
49            0 => Self::PosZero,
50            1 => Self::NegZero,
51            2 => Self::Negative,
52            3 => Self::Positive,
53            _ => unreachable!(),
54        }
55    }
56}
57
58/// Events that can occur in a pulse counter unit.
59#[derive(Copy, Clone, Debug, Default)]
60#[cfg_attr(feature = "defmt", derive(defmt::Format))]
61pub struct Events {
62    /// Sets when the pulse counter reaches the low limit.
63    pub low_limit: bool,
64    /// Sets when the pulse counter reaches the high limit.
65    pub high_limit: bool,
66    /// Sets when the pulse counter crosses threshold 0.
67    pub threshold0: bool,
68    /// Sets when the pulse counter crosses threshold 1.
69    pub threshold1: bool,
70    /// Sets when the pulse counter reaches zero.
71    pub zero: bool,
72}
73
74/// Represents a pulse counter unit.
75#[non_exhaustive]
76pub struct Unit<'d> {
77    unit: AnyPcntUnit<'d>,
78    /// The counter for PCNT unit.
79    pub counter: Counter<'d>,
80    /// The first channel in PCNT unit.
81    pub channel0: Channel<'d, 0>,
82    /// The second channel in PCNT unit.
83    pub channel1: Channel<'d, 1>,
84    _guard: PeripheralGuard,
85}
86
87impl<'d> Unit<'d> {
88    /// Returns a new PCNT unit.
89    pub fn new(unit: impl Instance + 'd) -> Self {
90        let (info, _) = unit.parts();
91        let guard = PeripheralGuard::new(info.peripheral);
92        #[cfg(soc_has_clock_node_pcnt_function_clock)]
93        ClockTree::with(|clocks| info.clock.request_function_clock(clocks));
94        let unit = unit.degrade();
95
96        let regs = info.regs();
97        regs.unit(info.unit).conf0().write(|w| unsafe { w.bits(0) });
98        info.lock(|| {
99            // Make sure the counter is reset
100            regs.ctrl()
101                .modify(|_, w| w.cnt_rst_u(info.unit as u8).set_bit());
102            let bits = regs.ctrl().read().bits();
103            regs.ctrl().write(|w| {
104                unsafe { w.bits(bits) };
105                w.cnt_rst_u(info.unit as u8).clear_bit();
106                // Make sure we don't stay paused in case this is a re-created unit
107                w.cnt_pause_u(info.unit as u8).clear_bit();
108                w.clk_en().set_bit()
109            });
110        });
111
112        Self {
113            counter: Counter::new(unsafe { unit.clone_unchecked() }),
114            channel0: Channel::new(unsafe { unit.clone_unchecked() }),
115            channel1: Channel::new(unsafe { unit.clone_unchecked() }),
116            unit,
117            _guard: guard,
118        }
119    }
120
121    fn index(&self) -> u8 {
122        self.unit.info().unit as u8
123    }
124
125    /// Configures a lower limit to the count value.
126    ///
127    /// When the count drops to this value:
128    /// - A low limit interrupt is triggered.
129    /// - The count is reset to 0.
130    ///
131    /// If None is specified, then no interrupt is triggered and
132    /// the count wraps around after [i16::MIN].
133    ///
134    /// The specified value must be negative.
135    pub fn set_low_limit(&self, value: Option<i16>) -> Result<(), InvalidLowLimit> {
136        let unit = self.unit.register_block().unit(self.unit.info().unit);
137
138        if let Some(value) = value {
139            // low limit must be >= or the limit is -32768 and when that's
140            // hit the event status claims it was the high limit.
141            // tested on an esp32s3
142            if !value.is_negative() {
143                return Err(InvalidLowLimit);
144            } else {
145                unit.conf2()
146                    .modify(|_, w| unsafe { w.cnt_l_lim().bits(value as u16) });
147                unit.conf0().modify(|_, w| w.thr_l_lim_en().set_bit());
148            }
149        } else {
150            unit.conf0().modify(|_, w| w.thr_l_lim_en().clear_bit());
151        }
152        Ok(())
153    }
154
155    /// Configures a high limit to the count value.
156    ///
157    /// When the count rises to this value:
158    /// - A high limit interrupt is triggered.
159    /// - The count is reset to 0.
160    ///
161    /// If None is specified, then no interrupt is triggered and
162    /// the count wraps around after [i16::MAX].
163    ///
164    /// The specified value must be positive.
165    pub fn set_high_limit(&self, value: Option<i16>) -> Result<(), InvalidHighLimit> {
166        let unit = self.unit.register_block().unit(self.unit.info().unit);
167
168        if let Some(value) = value {
169            if !value.is_positive() {
170                return Err(InvalidHighLimit);
171            } else {
172                unit.conf2()
173                    .modify(|_, w| unsafe { w.cnt_h_lim().bits(value as u16) });
174                unit.conf0().modify(|_, w| w.thr_h_lim_en().set_bit());
175            }
176        } else {
177            unit.conf0().modify(|_, w| w.thr_h_lim_en().clear_bit());
178        }
179        Ok(())
180    }
181
182    /// Configures a threshold value to trigger an interrupt.
183    ///
184    /// When the count equals this value a threshold0 interrupt is triggered.
185    /// If None is specified, then no interrupt is triggered.
186    pub fn set_threshold0(&self, value: Option<i16>) {
187        let unit = self.unit.register_block().unit(self.unit.info().unit);
188
189        if let Some(value) = value {
190            unit.conf1()
191                .modify(|_, w| unsafe { w.cnt_thres0().bits(value as u16) });
192            unit.conf0().modify(|_, w| w.thr_thres0_en().set_bit());
193        } else {
194            unit.conf0().modify(|_, w| w.thr_thres0_en().clear_bit());
195        }
196    }
197
198    /// Configures a threshold value to trigger an interrupt.
199    ///
200    /// When the count equals this value a threshold1 interrupt is triggered.
201    /// If None is specified, then no interrupt is triggered.
202    pub fn set_threshold1(&self, value: Option<i16>) {
203        let unit = self.unit.register_block().unit(self.unit.info().unit);
204
205        if let Some(value) = value {
206            unit.conf1()
207                .modify(|_, w| unsafe { w.cnt_thres1().bits(value as u16) });
208            unit.conf0().modify(|_, w| w.thr_thres1_en().set_bit());
209        } else {
210            unit.conf0().modify(|_, w| w.thr_thres1_en().clear_bit());
211        }
212    }
213
214    /// Configures the glitch filter hardware of the unit.
215    ///
216    /// `threshold` is the minimum number of APB_CLK cycles for a pulse to be
217    /// considered valid. If it is None, the filter is disabled.
218    ///
219    /// The maximum possible threshold is 1023.
220    pub fn set_filter(&self, threshold: Option<u16>) -> Result<(), InvalidFilterThreshold> {
221        let unit = self.unit.register_block().unit(self.unit.info().unit);
222
223        match threshold {
224            None => {
225                unit.conf0().modify(|_, w| w.filter_en().clear_bit());
226            }
227            Some(threshold) => {
228                if threshold > 1023 {
229                    return Err(InvalidFilterThreshold);
230                }
231                unit.conf0().modify(|_, w| unsafe {
232                    w.filter_thres().bits(threshold);
233                    w.filter_en().set_bit()
234                });
235            }
236        }
237        Ok(())
238    }
239
240    /// Resets the counter value to zero.
241    pub fn clear(&self) {
242        let n = self.index();
243        self.unit.lock(|| {
244            let regs = self.unit.register_block();
245            let bits = regs.ctrl().read().bits();
246            regs.ctrl().write(|w| {
247                unsafe { w.bits(bits) };
248                w.cnt_rst_u(n).set_bit()
249            });
250            regs.ctrl().write(|w| {
251                unsafe { w.bits(bits) };
252                w.cnt_rst_u(n).clear_bit()
253            });
254        });
255    }
256
257    /// Pauses the counter.
258    pub fn pause(&self) {
259        let n = self.index();
260        self.unit.lock(|| {
261            self.unit
262                .register_block()
263                .ctrl()
264                .modify(|_, w| w.cnt_pause_u(n).set_bit());
265        });
266    }
267
268    /// Resumes the counter.
269    pub fn resume(&self) {
270        let n = self.index();
271        self.unit.lock(|| {
272            self.unit
273                .register_block()
274                .ctrl()
275                .modify(|_, w| w.cnt_pause_u(n).clear_bit());
276        });
277    }
278
279    /// Returns the latest events for this unit.
280    pub fn events(&self) -> Events {
281        let status = self
282            .unit
283            .register_block()
284            .u_status(self.unit.info().unit)
285            .read();
286
287        Events {
288            low_limit: status.l_lim().bit(),
289            high_limit: status.h_lim().bit(),
290            threshold0: status.thres0().bit(),
291            threshold1: status.thres1().bit(),
292            zero: status.zero().bit(),
293        }
294    }
295
296    /// Returns the mode of the last zero crossing.
297    pub fn zero_mode(&self) -> ZeroMode {
298        self.unit
299            .register_block()
300            .u_status(self.unit.info().unit)
301            .read()
302            .zero_mode()
303            .bits()
304            .into()
305    }
306
307    /// Enables interrupts for this unit.
308    pub fn listen(&self) {
309        let n = self.index();
310        self.unit.lock(|| {
311            self.unit
312                .register_block()
313                .int_ena()
314                .modify(|_, w| w.cnt_thr_event_u(n).set_bit());
315        });
316    }
317
318    /// Disables interrupts for this unit.
319    pub fn unlisten(&self) {
320        let n = self.index();
321        self.unit.lock(|| {
322            self.unit
323                .register_block()
324                .int_ena()
325                .modify(|_, w| w.cnt_thr_event_u(n).clear_bit());
326        });
327    }
328
329    /// Returns whether an interrupt is active for this unit.
330    pub fn interrupt_is_set(&self) -> bool {
331        self.unit
332            .register_block()
333            .int_raw()
334            .read()
335            .cnt_thr_event_u(self.index())
336            .bit()
337    }
338
339    /// Clears the interrupt bit for this unit.
340    pub fn reset_interrupt(&self) {
341        self.unit
342            .register_block()
343            .int_clr()
344            .write(|w| w.cnt_thr_event_u(self.index()).set_bit());
345    }
346
347    /// Returns the current counter value.
348    pub fn value(&self) -> i16 {
349        self.counter.get()
350    }
351
352    /// Registers a handler invoked when this unit's interrupt status bit is
353    /// set.
354    ///
355    /// The hardware interrupt is shared by every unit in the same PCNT
356    /// register block. This method installs a dispatcher on that interrupt
357    /// and records `handler` for this unit only.
358    ///
359    /// This method ignores handler priority.
360    #[instability::unstable]
361    pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
362        let info = self.unit.info();
363        self.unit.state().store(handler.handler().callback());
364        crate::interrupt::bind_handler(info.interrupt, info.dispatcher);
365    }
366}
367
368impl crate::private::Sealed for Unit<'_> {}
369
370#[instability::unstable]
371impl InterruptConfigurable for Unit<'_> {
372    fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
373        self.set_interrupt_handler(handler);
374    }
375}
376
377impl Drop for Unit<'_> {
378    fn drop(&mut self) {
379        self.unlisten();
380        self.pause();
381        let info = self.unit.info();
382        info.regs()
383            .unit(info.unit)
384            .conf0()
385            .write(|w| unsafe { w.bits(0) });
386        self.unit.state().clear();
387        #[cfg(soc_has_clock_node_pcnt_function_clock)]
388        ClockTree::with(|clocks| info.clock.release_function_clock(clocks));
389    }
390}
391
392// The entire Unit is Send but the individual channels are not.
393unsafe impl Send for Unit<'_> {}
394
395/// Represents the counter within a pulse counter unit.
396pub struct Counter<'d> {
397    unit: AnyPcntUnit<'d>,
398    _guard: PeripheralGuard,
399}
400
401impl Clone for Counter<'_> {
402    fn clone(&self) -> Self {
403        Self {
404            unit: unsafe { self.unit.clone_unchecked() },
405            _guard: self._guard.clone(),
406        }
407    }
408}
409
410impl<'d> Counter<'d> {
411    fn new(unit: AnyPcntUnit<'d>) -> Self {
412        let guard = PeripheralGuard::new(unit.info().peripheral);
413
414        Self {
415            unit,
416            _guard: guard,
417        }
418    }
419
420    /// Returns the current counter value.
421    pub fn get(&self) -> i16 {
422        self.unit
423            .register_block()
424            .u_cnt(self.unit.info().unit)
425            .read()
426            .cnt()
427            .bits() as i16
428    }
429}