esp-hal 1.2.0

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
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
use core::{
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

// Both SAR units report completion through the single LP_ADC interrupt line.
use Interrupt::LP_ADC as InterruptSource;
// Both units share one interrupt, so the enabled instances have to be counted.
use portable_atomic::{AtomicU32, Ordering};
use procmacros::handler;

use super::{AdcCalScheme, AdcChannel, AdcConfig, AdcPin};
use crate::{
    Async,
    Blocking,
    asynch::AtomicWaker,
    interrupt::{InterruptConfigurable, InterruptHandler},
    peripherals::{APB_SARADC, Interrupt, LP_PERI},
    rtc_cntl::WakeLock,
    system::{GenericPeripheralGuard, Peripheral},
};

/// Both units have 8 channels, and the attenuation table is indexed by channel.
pub(super) const NUM_ATTENS: usize = 8;

/// Mask of the conversion data in `sarN_data_status`. The rest of the register
/// holds the channel and the unit that produced the sample.
const ADC_DATA_MASK: u32 = 0x1_ffff;

/// The largest value a conversion can return.
///
/// The SAR has 17 redundant comparator bits with non-uniform weights, and the
/// hardware reports their weighted sum. The result is therefore not a 17-bit
/// number: it spans a little more than 12 bits.
///
/// See `adc_digi_output_data_t` for the ESP32-S31 in
/// `components/esp_hal_ana_conv/include/hal/adc_types.h`.
#[instability::unstable]
pub const FULL_SCALE: u16 = 4393;

/// The value a conversion returns for a zero input difference.
///
/// The SAR is differential, so an input tied to ground reads about this value
/// instead of zero, and only the codes above it are available to a single-ended
/// measurement.
///
/// See `ADC_LL_ZERO_DIFF_CODE` in
/// `components/esp_hal_ana_conv/esp32s31/include/hal/adc_ll.h`.
#[instability::unstable]
pub const ZERO_DIFF_CODE: u16 = 2198;

/// Software trigger mode, used for one-shot conversions.
const TRIGGER_MODE_SW: u8 = 2;
/// Trigger disabled.
const TRIGGER_MODE_OFF: u8 = 0;

/// Powers the SAR up by software, instead of leaving it to the FSM.
const FORCE_XPD_SAR_PU: u8 = 3;

/// Clock divider for the digital controller. The divider is `CLK_DIV_NUM + 1`.
///
/// See `ADC_LL_CLKM_DIV_NUM_DEFAULT` in
/// `components/esp_hal_ana_conv/esp32s31/include/hal/adc_ll.h`.
const CLK_DIV_NUM: u8 = 4;

/// Digital controller clock source select value for XTAL.
const CLK_SRC_XTAL: u8 = 1;

/// Enables the reference generator shared by both units.
fn enable_refgen() {
    APB_SARADC::regs().ref_control().modify(|_, w| {
        w.rtc_xpd_refgen().set_bit();
        w.rtc_pre_charge().set_bit();
        w.rtc_ref_delay().set_bit()
    });
}

#[doc(hidden)]
pub trait RegisterAccess {
    /// Powers the SAR up and puts the unit into single-conversion mode.
    fn enable();

    /// Programs the single-entry pattern table with the given channel.
    fn program_pattern(channel: u8);

    /// Triggers one conversion.
    fn start_sample();

    /// Returns whether sampling is done.
    fn is_done() -> bool;

    /// Reads sample data.
    fn read_data() -> u16;

    /// Clears the done flag and stops triggering.
    fn reset();
}

#[cfg(adc_adc1)]
impl RegisterAccess for crate::peripherals::ADC1<'_> {
    fn enable() {
        APB_SARADC::regs()
            .ctrl2()
            .modify(|_, w| w.timer_en().clear_bit());

        enable_refgen();

        APB_SARADC::regs().ctrl0().modify(|_, w| unsafe {
            w.xpd_sar1_force().bits(FORCE_XPD_SAR_PU);
            w.sar1_continue_mode_en().clear_bit();
            w.sar1_trigger_stop().set_bit()
        });
    }

    fn program_pattern(channel: u8) {
        let regs = APB_SARADC::regs();

        // Each pattern entry is 6 bits wide and the first entry occupies the
        // most significant bits of the 24-bit table.
        let entry = (((channel & 0xf) as u32) << 2) << 18;

        regs.ctrl0().modify(|_, w| unsafe {
            w.sar1_patt_type().set_bit();
            w.sar1_patt_len().bits(0)
        });
        regs.sar1_patt_tab1()
            .write(|w| unsafe { w.sar1_patt_tab1().bits(entry) });

        regs.ctrl0().modify(|_, w| w.sar1_patt_p_clear().set_bit());
        regs.ctrl0()
            .modify(|_, w| w.sar1_patt_p_clear().clear_bit());

        regs.ctrl0()
            .modify(|_, w| unsafe { w.sar1_trigger_mode().bits(TRIGGER_MODE_SW) });
    }

    fn start_sample() {
        APB_SARADC::regs()
            .ctrl0()
            .modify(|_, w| w.sar1_trigger_start().set_bit());
    }

    fn is_done() -> bool {
        APB_SARADC::regs().int_raw().read().sar1_done().bit_is_set()
    }

    fn read_data() -> u16 {
        (APB_SARADC::regs()
            .sar1_data_status()
            .read()
            .apb_saradc1_data()
            .bits()
            & ADC_DATA_MASK) as u16
    }

    fn reset() {
        APB_SARADC::regs()
            .int_clr()
            .write(|w| w.sar1_done().clear_bit_by_one());

        APB_SARADC::regs()
            .ctrl0()
            .modify(|_, w| unsafe { w.sar1_trigger_mode().bits(TRIGGER_MODE_OFF) });
    }
}

#[cfg(adc_adc2)]
impl RegisterAccess for crate::peripherals::ADC2<'_> {
    fn enable() {
        APB_SARADC::regs()
            .ctrl2()
            .modify(|_, w| w.timer_en().clear_bit());

        enable_refgen();

        APB_SARADC::regs().ctrl1().modify(|_, w| unsafe {
            w.xpd_sar2_force().bits(FORCE_XPD_SAR_PU);
            w.sar2_continue_mode_en().clear_bit();
            w.sar2_trigger_stop().set_bit()
        });
    }

    fn program_pattern(channel: u8) {
        let regs = APB_SARADC::regs();

        let entry = (((channel & 0xf) as u32) << 2) << 18;

        regs.ctrl1().modify(|_, w| unsafe {
            w.sar2_patt_type().set_bit();
            w.sar2_patt_len().bits(0)
        });
        regs.sar2_patt_tab1()
            .write(|w| unsafe { w.sar2_patt_tab1().bits(entry) });

        regs.ctrl1().modify(|_, w| w.sar2_patt_p_clear().set_bit());
        regs.ctrl1()
            .modify(|_, w| w.sar2_patt_p_clear().clear_bit());

        regs.ctrl1()
            .modify(|_, w| unsafe { w.sar2_trigger_mode().bits(TRIGGER_MODE_SW) });
    }

    fn start_sample() {
        APB_SARADC::regs()
            .ctrl1()
            .modify(|_, w| w.sar2_trigger_start().set_bit());
    }

    fn is_done() -> bool {
        APB_SARADC::regs().int_raw().read().sar2_done().bit_is_set()
    }

    fn read_data() -> u16 {
        (APB_SARADC::regs()
            .sar2_data_status()
            .read()
            .apb_saradc2_data()
            .bits()
            & ADC_DATA_MASK) as u16
    }

    fn reset() {
        APB_SARADC::regs()
            .int_clr()
            .write(|w| w.sar2_done().clear_bit_by_one());

        APB_SARADC::regs()
            .ctrl1()
            .modify(|_, w| unsafe { w.sar2_trigger_mode().bits(TRIGGER_MODE_OFF) });
    }
}

/// Analog-to-Digital Converter peripheral driver.
pub struct Adc<'d, ADC, Dm: crate::DriverMode> {
    _adc: ADC,
    active_channel: Option<u8>,
    _guard: GenericPeripheralGuard<{ Peripheral::ApbSarAdc as u8 }>,
    _phantom: PhantomData<(Dm, &'d mut ())>,
}

impl<'d, ADCX> Adc<'d, ADCX, Blocking>
where
    ADCX: RegisterAccess + 'd,
{
    /// Configures a given ADC instance using the provided configuration, and
    /// initializes the ADC for use.
    ///
    /// The ESP32-S31 SAR ADC has a single attenuation setting, so the
    /// attenuation given per pin has no effect.
    pub fn new(adc_instance: ADCX, _config: AdcConfig<ADCX>) -> Self {
        let guard = GenericPeripheralGuard::new();

        // Select XTAL as the digital controller clock and divide it down.
        LP_PERI::regs().adc_ctrl().modify(|_, w| unsafe {
            w.lp_adc_clk_sel().bits(CLK_SRC_XTAL);
            w.lp_adc_div_num().bits(CLK_DIV_NUM)
        });

        // Function clock of the digital controller.
        APB_SARADC::regs()
            .ctrl_date()
            .modify(|_, w| w.clk_en().set_bit());

        ADCX::enable();

        Adc {
            _adc: adc_instance,
            active_channel: None,
            _guard: guard,
            _phantom: PhantomData,
        }
    }

    /// Reconfigures the ADC driver to operate in asynchronous mode.
    pub fn into_async(mut self) -> Adc<'d, ADCX, Async> {
        acquire_async_adc();
        self.set_interrupt_handler(adc_interrupt_handler);

        // Clear a stale done flag so that the first future does not complete early.
        ADCX::reset();

        Adc {
            _adc: self._adc,
            active_channel: self.active_channel,
            _guard: self._guard,
            _phantom: PhantomData,
        }
    }

    /// Starts and waits for a conversion on the specified pin and returns the
    /// result.
    ///
    /// The result is in the range 0..=[`FULL_SCALE`], and an input tied to
    /// ground reads about [`ZERO_DIFF_CODE`].
    pub fn read_blocking<PIN, CS>(&mut self, pin: &mut AdcPin<PIN, ADCX, CS>) -> u16
    where
        PIN: AdcChannel,
        CS: AdcCalScheme<ADCX>,
    {
        ADCX::program_pattern(pin.pin.adc_channel());
        ADCX::start_sample();

        while !ADCX::is_done() {}

        let converted_value = ADCX::read_data();
        ADCX::reset();

        converted_value
    }

    /// Requests that the ADC begin a conversion on the specified pin.
    ///
    /// Takes an [`AdcPin`](super::AdcPin) reference, as it is
    /// expected that the ADC will be able to sample whatever channel
    /// underlies the pin.
    ///
    /// The result is in the range 0..=[`FULL_SCALE`], and an input tied to
    /// ground reads about [`ZERO_DIFF_CODE`].
    pub fn read_oneshot<PIN, CS>(
        &mut self,
        pin: &mut super::AdcPin<PIN, ADCX, CS>,
    ) -> nb::Result<u16, ()>
    where
        PIN: super::AdcChannel,
        CS: super::AdcCalScheme<ADCX>,
    {
        if let Some(active_channel) = self.active_channel {
            // There is conversion in progress:
            // - if it's for a different channel try again later
            // - if it's for the given channel, go ahead and check progress
            if active_channel != pin.pin.adc_channel() {
                return Err(nb::Error::WouldBlock);
            }
        } else {
            // If no conversions are in progress, start a new one for given channel
            self.active_channel = Some(pin.pin.adc_channel());

            ADCX::program_pattern(pin.pin.adc_channel());
            ADCX::start_sample();
        }

        if !ADCX::is_done() {
            return Err(nb::Error::WouldBlock);
        }

        let converted_value = ADCX::read_data();
        ADCX::reset();

        // Mark that no conversions are currently in progress
        self.active_channel = None;

        Ok(converted_value)
    }
}

impl<ADCX> crate::private::Sealed for Adc<'_, ADCX, Blocking> {}

impl<ADCX> InterruptConfigurable for Adc<'_, ADCX, Blocking> {
    fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
        for core in crate::system::Cpu::other() {
            crate::interrupt::disable(core, InterruptSource);
        }
        crate::interrupt::bind_handler(InterruptSource, handler);
    }
}

impl<'d, ADCX> Adc<'d, ADCX, Async>
where
    ADCX: RegisterAccess + 'd,
{
    /// Reconfigures the ADC driver to operate in [`Blocking`] mode.
    pub fn into_blocking(self) -> Adc<'d, ADCX, Blocking> {
        if release_async_adc() {
            // Disable the ADC interrupt on all cores once the last async instance goes away.
            for cpu in crate::system::Cpu::all() {
                crate::interrupt::disable(cpu, InterruptSource);
            }
        }
        Adc {
            _adc: self._adc,
            active_channel: self.active_channel,
            _guard: self._guard,
            _phantom: PhantomData,
        }
    }

    /// Starts a conversion on the specified pin and waits for the result.
    ///
    /// Takes an [`AdcPin`](super::AdcPin) reference, as it is
    /// expected that the ADC will be able to sample whatever channel
    /// underlies the pin.
    ///
    /// The result is in the range 0..=[`FULL_SCALE`], and an input tied to
    /// ground reads about [`ZERO_DIFF_CODE`].
    pub async fn read_oneshot<PIN, CS>(&mut self, pin: &mut super::AdcPin<PIN, ADCX, CS>) -> u16
    where
        ADCX: Instance,
        PIN: super::AdcChannel,
        CS: super::AdcCalScheme<ADCX>,
    {
        ADCX::program_pattern(pin.pin.adc_channel());
        ADCX::start_sample();

        AdcFuture::<ADCX>::new(self).await;

        let converted_value = ADCX::read_data();
        ADCX::reset();

        converted_value
    }
}

static ASYNC_ADC_COUNT: AtomicU32 = AtomicU32::new(0);

fn acquire_async_adc() {
    ASYNC_ADC_COUNT.fetch_add(1, Ordering::Relaxed);
}

fn release_async_adc() -> bool {
    ASYNC_ADC_COUNT.fetch_sub(1, Ordering::Relaxed) == 1
}

#[handler]
pub(crate) fn adc_interrupt_handler() {
    let interrupt_status = APB_SARADC::regs().int_st().read();

    #[cfg(adc_adc1)]
    if interrupt_status.sar1_done().bit_is_set() {
        unsafe { handle_async(crate::peripherals::ADC1::steal()) }
    }

    #[cfg(adc_adc2)]
    if interrupt_status.sar2_done().bit_is_set() {
        unsafe { handle_async(crate::peripherals::ADC2::steal()) }
    }
}

fn handle_async<ADCX: Instance>(_instance: ADCX) {
    ADCX::waker().wake();
    ADCX::unlisten();
}

/// Enables asynchronous access.
pub trait Instance: crate::private::Sealed {
    /// Enables the ADC interrupt.
    fn listen();

    /// Disables the ADC interrupt.
    fn unlisten();

    /// Clears the ADC interrupt.
    fn clear_interrupt();

    /// Obtains the waker for the ADC interrupt.
    fn waker() -> &'static AtomicWaker;
}

#[cfg(adc_adc1)]
impl Instance for crate::peripherals::ADC1<'_> {
    fn listen() {
        APB_SARADC::regs()
            .int_ena()
            .modify(|_, w| w.sar1_done().set_bit());
    }

    fn unlisten() {
        APB_SARADC::regs()
            .int_ena()
            .modify(|_, w| w.sar1_done().clear_bit());
    }

    fn clear_interrupt() {
        APB_SARADC::regs()
            .int_clr()
            .write(|w| w.sar1_done().clear_bit_by_one());
    }

    fn waker() -> &'static AtomicWaker {
        static WAKER: AtomicWaker = AtomicWaker::new();

        &WAKER
    }
}

#[cfg(adc_adc2)]
impl Instance for crate::peripherals::ADC2<'_> {
    fn listen() {
        APB_SARADC::regs()
            .int_ena()
            .modify(|_, w| w.sar2_done().set_bit());
    }

    fn unlisten() {
        APB_SARADC::regs()
            .int_ena()
            .modify(|_, w| w.sar2_done().clear_bit());
    }

    fn clear_interrupt() {
        APB_SARADC::regs()
            .int_clr()
            .write(|w| w.sar2_done().clear_bit_by_one());
    }

    fn waker() -> &'static AtomicWaker {
        static WAKER: AtomicWaker = AtomicWaker::new();

        &WAKER
    }
}

#[must_use = "futures do nothing unless you `.await` or poll them"]
pub(crate) struct AdcFuture<ADCX: Instance> {
    phantom: PhantomData<ADCX>,
    _wake_lock: WakeLock,
}

impl<ADCX: Instance> AdcFuture<ADCX> {
    pub fn new(_self: &super::Adc<'_, ADCX, Async>) -> Self {
        Self {
            phantom: PhantomData,
            _wake_lock: WakeLock::new(),
        }
    }
}

impl<ADCX: Instance + super::RegisterAccess> core::future::Future for AdcFuture<ADCX> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if ADCX::is_done() {
            ADCX::clear_interrupt();
            Poll::Ready(())
        } else {
            ADCX::waker().register(cx.waker());
            ADCX::listen();
            Poll::Pending
        }
    }
}

impl<ADCX: Instance> Drop for AdcFuture<ADCX> {
    fn drop(&mut self) {
        ADCX::unlisten();
    }
}