esp-hal 0.16.1

Bare-metal HAL for Espressif devices
Documentation
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
//! # PCNT - Unit module
//!
//! ## Overview
//! The `unit` module is a part of the `PCNT` peripheral driver
//! for ESP chips. It offers functionalities for configuring and utilizing
//! specific units of the PCNT peripheral.
//!
//! Each unit is identified by a unit number, such as `Unit0`, `Unit1`, `Unit2`,
//! and so on. This module provides methods to configure a unit with specific
//! settings, like low and high limits, thresholds, and optional filtering.
//! Users can easily configure these units based on their requirements.

use critical_section::CriticalSection;

use super::channel;

/// Unit number
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum Number {
    Unit0,
    Unit1,
    Unit2,
    Unit3,
    #[cfg(esp32)]
    Unit4,
    #[cfg(esp32)]
    Unit5,
    #[cfg(esp32)]
    Unit6,
    #[cfg(esp32)]
    Unit7,
}

/// Unit errors
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// Invalid filter threshold value
    InvalidFilterThresh,
    /// Invalid low limit - must be < 0
    InvalidLowLimit,
    /// Invalid high limit - must be > 0
    InvalidHighLimit,
}

/// the current status of the counter.
#[derive(Copy, Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ZeroMode {
    /// pulse counter decreases from positive to 0.
    #[default]
    PosZero  = 0,
    /// pulse counter increases from negative to 0
    NegZero  = 1,
    /// pulse counter is negative (not implemented?)
    Negitive = 2,
    /// pulse counter is positive (not implemented?)
    Positive = 3,
}

impl From<u8> for ZeroMode {
    fn from(value: u8) -> Self {
        match value {
            0 => Self::PosZero,
            1 => Self::NegZero,
            2 => Self::Negitive,
            3 => Self::Positive,
            _ => unreachable!(), // TODO: is this good enoough?  should we use some default?
        }
    }
}

// Events
#[derive(Copy, Clone, Debug, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Events {
    pub low_limit: bool,
    pub high_limit: bool,
    pub thresh0: bool,
    pub thresh1: bool,
    pub zero: bool,
}

/// Unit configuration
#[derive(Copy, Clone, Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Config {
    pub low_limit: i16,
    pub high_limit: i16,
    pub thresh0: i16,
    pub thresh1: i16,
    pub filter: Option<u16>,
}

pub struct Unit {
    number: Number,
}

impl Unit {
    /// return a new Unit
    pub(super) fn new(number: Number) -> Self {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        let conf0 = match number {
            Number::Unit0 => pcnt.u0_conf0(),
            Number::Unit1 => pcnt.u1_conf0(),
            Number::Unit2 => pcnt.u2_conf0(),
            Number::Unit3 => pcnt.u3_conf0(),
            #[cfg(esp32)]
            Number::Unit4 => pcnt.u4_conf0(),
            #[cfg(esp32)]
            Number::Unit5 => pcnt.u5_conf0(),
            #[cfg(esp32)]
            Number::Unit6 => pcnt.u6_conf0(),
            #[cfg(esp32)]
            Number::Unit7 => pcnt.u7_conf0(),
        };
        // disable filter and all events
        conf0.modify(|_, w| unsafe {
            w.filter_en()
                .clear_bit()
                .filter_thres()
                .bits(0)
                .thr_l_lim_en()
                .clear_bit()
                .thr_h_lim_en()
                .clear_bit()
                .thr_thres0_en()
                .clear_bit()
                .thr_thres1_en()
                .clear_bit()
                .thr_zero_en()
                .clear_bit()
        });
        Self { number }
    }

    pub fn configure(&mut self, config: Config) -> Result<(), Error> {
        // low limit must be >= or the limit is -32768 and when thats
        // hit the event status claims it was the high limit.
        // tested on an esp32s3
        if config.low_limit >= 0 {
            return Err(Error::InvalidLowLimit);
        }
        if config.high_limit <= 0 {
            return Err(Error::InvalidHighLimit);
        }
        let (filter_en, filter) = match config.filter {
            Some(filter) => (true, filter),
            None => (false, 0),
        };
        // filter must be less than 1024
        if filter > 1023 {
            return Err(Error::InvalidFilterThresh);
        }

        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        let (conf0, conf1, conf2) = match self.number {
            Number::Unit0 => (pcnt.u0_conf0(), pcnt.u0_conf1(), pcnt.u0_conf2()),
            Number::Unit1 => (pcnt.u1_conf0(), pcnt.u1_conf1(), pcnt.u1_conf2()),
            Number::Unit2 => (pcnt.u2_conf0(), pcnt.u2_conf1(), pcnt.u2_conf2()),
            Number::Unit3 => (pcnt.u3_conf0(), pcnt.u3_conf1(), pcnt.u3_conf2()),
            #[cfg(esp32)]
            Number::Unit4 => (pcnt.u4_conf0(), pcnt.u4_conf1(), pcnt.u4_conf2()),
            #[cfg(esp32)]
            Number::Unit5 => (pcnt.u5_conf0(), pcnt.u5_conf1(), pcnt.u5_conf2()),
            #[cfg(esp32)]
            Number::Unit6 => (pcnt.u6_conf0(), pcnt.u6_conf1(), pcnt.u6_conf2()),
            #[cfg(esp32)]
            Number::Unit7 => (pcnt.u7_conf0(), pcnt.u7_conf1(), pcnt.u7_conf2()),
        };
        conf2.write(|w| unsafe {
            w.cnt_l_lim()
                .bits(config.low_limit as u16)
                .cnt_h_lim()
                .bits(config.high_limit as u16)
        });
        conf1.write(|w| unsafe {
            w.cnt_thres0()
                .bits(config.thresh0 as u16)
                .cnt_thres1()
                .bits(config.thresh1 as u16)
        });
        conf0.modify(|_, w| unsafe { w.filter_thres().bits(filter).filter_en().bit(filter_en) });
        self.pause();
        self.clear();
        Ok(())
    }

    pub fn get_channel(&self, number: channel::Number) -> super::channel::Channel {
        super::channel::Channel::new(self.number, number)
    }

    pub fn clear(&self) {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        critical_section::with(|_cs| {
            match self.number {
                Number::Unit0 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u0().set_bit()),
                Number::Unit1 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u1().set_bit()),
                Number::Unit2 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u2().set_bit()),
                Number::Unit3 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u3().set_bit()),
                #[cfg(esp32)]
                Number::Unit4 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u4().set_bit()),
                #[cfg(esp32)]
                Number::Unit5 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u5().set_bit()),
                #[cfg(esp32)]
                Number::Unit6 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u6().set_bit()),
                #[cfg(esp32)]
                Number::Unit7 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u7().set_bit()),
            }
            // TODO: does this need a delay? (liebman / Jan 2 2023)
            match self.number {
                Number::Unit0 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u0().clear_bit()),
                Number::Unit1 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u1().clear_bit()),
                Number::Unit2 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u2().clear_bit()),
                Number::Unit3 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u3().clear_bit()),
                #[cfg(esp32)]
                Number::Unit4 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u4().clear_bit()),
                #[cfg(esp32)]
                Number::Unit5 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u5().clear_bit()),
                #[cfg(esp32)]
                Number::Unit6 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u6().clear_bit()),
                #[cfg(esp32)]
                Number::Unit7 => pcnt.ctrl().modify(|_, w| w.cnt_rst_u7().clear_bit()),
            }
        });
    }

    /// Pause the counter
    pub fn pause(&self) {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        critical_section::with(|_cs| match self.number {
            Number::Unit0 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u0().set_bit()),
            Number::Unit1 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u1().set_bit()),
            Number::Unit2 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u2().set_bit()),
            Number::Unit3 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u3().set_bit()),
            #[cfg(esp32)]
            Number::Unit4 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u4().set_bit()),
            #[cfg(esp32)]
            Number::Unit5 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u5().set_bit()),
            #[cfg(esp32)]
            Number::Unit6 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u6().set_bit()),
            #[cfg(esp32)]
            Number::Unit7 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u7().set_bit()),
        });
    }

    /// Resume the counter
    pub fn resume(&self) {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        critical_section::with(|_cs| match self.number {
            Number::Unit0 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u0().clear_bit()),
            Number::Unit1 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u1().clear_bit()),
            Number::Unit2 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u2().clear_bit()),
            Number::Unit3 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u3().clear_bit()),
            #[cfg(esp32)]
            Number::Unit4 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u4().clear_bit()),
            #[cfg(esp32)]
            Number::Unit5 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u5().clear_bit()),
            #[cfg(esp32)]
            Number::Unit6 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u6().clear_bit()),
            #[cfg(esp32)]
            Number::Unit7 => pcnt.ctrl().modify(|_, w| w.cnt_pause_u7().clear_bit()),
        });
    }

    /// Enable which events generate interrupts on this unit.
    pub fn events(&self, events: Events) {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        let conf0 = match self.number {
            Number::Unit0 => pcnt.u0_conf0(),
            Number::Unit1 => pcnt.u1_conf0(),
            Number::Unit2 => pcnt.u2_conf0(),
            Number::Unit3 => pcnt.u3_conf0(),
            #[cfg(esp32)]
            Number::Unit4 => pcnt.u4_conf0(),
            #[cfg(esp32)]
            Number::Unit5 => pcnt.u5_conf0(),
            #[cfg(esp32)]
            Number::Unit6 => pcnt.u6_conf0(),
            #[cfg(esp32)]
            Number::Unit7 => pcnt.u7_conf0(),
        };
        conf0.modify(|_, w| {
            w.thr_l_lim_en()
                .bit(events.low_limit)
                .thr_h_lim_en()
                .bit(events.high_limit)
                .thr_thres0_en()
                .bit(events.thresh0)
                .thr_thres1_en()
                .bit(events.thresh1)
                .thr_zero_en()
                .bit(events.zero)
        });
    }

    /// Get the latest events for this unit.
    pub fn get_events(&self) -> Events {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        let status = pcnt.u_status(self.number as usize).read();

        Events {
            low_limit: status.l_lim().bit(),
            high_limit: status.h_lim().bit(),
            thresh0: status.thres0().bit(),
            thresh1: status.thres1().bit(),
            zero: status.zero().bit(),
        }
    }

    /// Get the mode of the last zero crossing
    pub fn get_zero_mode(&self) -> ZeroMode {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        pcnt.u_status(self.number as usize)
            .read()
            .zero_mode()
            .bits()
            .into()
    }

    /// Enable interrupts for this unit.
    pub fn listen(&self) {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        critical_section::with(|_cs| {
            pcnt.int_ena().modify(|_, w| match self.number {
                Number::Unit0 => w.cnt_thr_event_u0().set_bit(),
                Number::Unit1 => w.cnt_thr_event_u1().set_bit(),
                Number::Unit2 => w.cnt_thr_event_u2().set_bit(),
                Number::Unit3 => w.cnt_thr_event_u3().set_bit(),
                #[cfg(esp32)]
                Number::Unit4 => w.cnt_thr_event_u4().set_bit(),
                #[cfg(esp32)]
                Number::Unit5 => w.cnt_thr_event_u5().set_bit(),
                #[cfg(esp32)]
                Number::Unit6 => w.cnt_thr_event_u6().set_bit(),
                #[cfg(esp32)]
                Number::Unit7 => w.cnt_thr_event_u7().set_bit(),
            })
        });
    }

    /// Disable interrupts for this unit.
    pub fn unlisten(&self, _cs: CriticalSection) {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        critical_section::with(|_cs| {
            pcnt.int_ena().write(|w| match self.number {
                Number::Unit0 => w.cnt_thr_event_u0().clear_bit(),
                Number::Unit1 => w.cnt_thr_event_u1().clear_bit(),
                Number::Unit2 => w.cnt_thr_event_u2().clear_bit(),
                Number::Unit3 => w.cnt_thr_event_u3().clear_bit(),
                #[cfg(esp32)]
                Number::Unit4 => w.cnt_thr_event_u4().clear_bit(),
                #[cfg(esp32)]
                Number::Unit5 => w.cnt_thr_event_u5().clear_bit(),
                #[cfg(esp32)]
                Number::Unit6 => w.cnt_thr_event_u6().clear_bit(),
                #[cfg(esp32)]
                Number::Unit7 => w.cnt_thr_event_u7().clear_bit(),
            })
        });
    }

    /// Returns true if an interrupt is active for this unit.
    pub fn interrupt_set(&self) -> bool {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        match self.number {
            Number::Unit0 => pcnt.int_st().read().cnt_thr_event_u0().bit(),
            Number::Unit1 => pcnt.int_st().read().cnt_thr_event_u1().bit(),
            Number::Unit2 => pcnt.int_st().read().cnt_thr_event_u2().bit(),
            Number::Unit3 => pcnt.int_st().read().cnt_thr_event_u3().bit(),
            #[cfg(esp32)]
            Number::Unit4 => pcnt.int_st().read().cnt_thr_event_u4().bit(),
            #[cfg(esp32)]
            Number::Unit5 => pcnt.int_st().read().cnt_thr_event_u5().bit(),
            #[cfg(esp32)]
            Number::Unit6 => pcnt.int_st().read().cnt_thr_event_u6().bit(),
            #[cfg(esp32)]
            Number::Unit7 => pcnt.int_st().read().cnt_thr_event_u7().bit(),
        }
    }

    /// Clear the interrupt bit for this unit.
    pub fn reset_interrupt(&self) {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        critical_section::with(|_cs| {
            pcnt.int_clr().write(|w| match self.number {
                Number::Unit0 => w.cnt_thr_event_u0().set_bit(),
                Number::Unit1 => w.cnt_thr_event_u1().set_bit(),
                Number::Unit2 => w.cnt_thr_event_u2().set_bit(),
                Number::Unit3 => w.cnt_thr_event_u3().set_bit(),
                #[cfg(esp32)]
                Number::Unit4 => w.cnt_thr_event_u4().set_bit(),
                #[cfg(esp32)]
                Number::Unit5 => w.cnt_thr_event_u5().set_bit(),
                #[cfg(esp32)]
                Number::Unit6 => w.cnt_thr_event_u6().set_bit(),
                #[cfg(esp32)]
                Number::Unit7 => w.cnt_thr_event_u7().set_bit(),
            })
        });
    }

    /// Get the current counter value.
    pub fn get_value(&self) -> i16 {
        let pcnt = unsafe { &*crate::peripherals::PCNT::ptr() };
        pcnt.u_cnt(self.number as usize).read().cnt().bits() as i16
    }
}