Skip to main content

esp_hal/analog/adc/
s2_s3.rs

1use core::{
2    marker::PhantomData,
3    pin::Pin,
4    task::{Context, Poll},
5};
6
7use portable_atomic::{AtomicU32, Ordering};
8use procmacros::{handler, ram};
9
10pub use self::calibration::*;
11use super::{AdcCalScheme, AdcChannel, AdcConfig, AdcPin, Attenuation, Error};
12use crate::{
13    Async,
14    Blocking,
15    asynch::AtomicWaker,
16    efuse::AdcCalibUnit,
17    interrupt::{InterruptConfigurable, InterruptHandler},
18    peripherals::{APB_SARADC, Interrupt, LPWR, SENS},
19    rtc_cntl::WakeLock,
20    soc::regi2c,
21    system::{GenericPeripheralGuard, Peripheral},
22};
23
24mod calibration;
25
26pub(super) const NUM_ATTENS: usize = 10;
27
28cfg_select! {
29    esp32s2 => {
30        const ADC_VAL_MASK: u16 = 0x1fff;
31    }
32    esp32s3 => {
33        const ADC_VAL_MASK: u16 = 0xfff;
34    }
35}
36
37impl<ADCX> AdcConfig<ADCX>
38where
39    ADCX: RegisterAccess,
40{
41    /// Measures the initial code that cancels the unit's zero-voltage offset at `atten`.
42    pub fn adc_calibrate(atten: Attenuation) -> u16
43    where
44        ADCX: super::CalibrationAccess,
45    {
46        // This can be called without an `Adc`, so it cannot rely on `Adc::new` having powered up
47        // the unit.
48        let _guard = GenericPeripheralGuard::<{ Peripheral::ApbSarAdc as u8 }>::new();
49        init_hardware::<ADCX>();
50
51        ADCX::enable_vdef(true);
52
53        // Start sampling
54        ADCX::setup_calibration(atten);
55
56        // Connect calibration source
57        ADCX::connect_gnd(true);
58
59        ADCX::calibration_init();
60        let cal_val = super::search_init_code::<ADCX>(|| {
61            // Clearing the done flag up front, rather than after the read, keeps a conversion left
62            // over from the previous code from being mistaken for this one's result.
63            ADCX::reset();
64            ADCX::start_sample();
65            while !ADCX::is_done() {}
66
67            ADCX::read_data() & ADCX::ADC_VAL_MASK
68        });
69        ADCX::reset();
70
71        // Disconnect calibration source
72        ADCX::connect_gnd(false);
73
74        cal_val
75    }
76}
77
78/// Routes the unit to the RTC controller and powers it up.
79///
80/// Writes nothing that depends on previous state, so it is safe to run more than once.
81fn init_hardware<ADCX: RegisterAccess>() {
82    let sensors = SENS::regs();
83
84    // Set controller to RTC
85    ADCX::clear_dig_force();
86    ADCX::set_start_force();
87    ADCX::set_en_pad_force();
88    sensors.sar_hall_ctrl().modify(|_, w| {
89        w.xpd_hall_force().set_bit();
90        w.hall_phase_force().set_bit()
91    });
92
93    cfg_select! {
94        esp32s2 => {
95            sensors
96                .sar_meas1_ctrl1()
97                .modify(|_, w| w.rtc_saradc_clkgate_en().set_bit());
98        }
99        esp32s3 => {
100            crate::system::PeripheralClockControl::set_enabled_untracked(Peripheral::SarAdc, true)
101        }
102    }
103
104    sensors.sar_power_xpd_sar().modify(|_, w| unsafe {
105        w.sarclk_en().set_bit();
106        // Force the SAR ADC on.
107        w.force_xpd_sar().bits(0b11)
108    });
109
110    ADCX::set_sar_clk_div();
111
112    // disable AMP
113    sensors
114        .sar_meas1_ctrl1()
115        .modify(|_, w| unsafe { w.force_xpd_amp().bits(0b11) });
116    let configure_amp = || {
117        sensors.sar_amp_ctrl3().modify(|_, w| unsafe {
118            w.amp_rst_fb_fsm().bits(0);
119            w.amp_short_ref_fsm().bits(0);
120            w.amp_short_ref_gnd_fsm().bits(0)
121        });
122    };
123    cfg_select! {
124        esp32s2 => crate::analog::ADC_DAC_LOCK.lock(configure_amp),
125        _ => configure_amp(),
126    }
127    sensors.sar_amp_ctrl1().modify(|_, w| unsafe {
128        w.sar_amp_wait1().bits(1);
129        w.sar_amp_wait2().bits(1)
130    });
131    sensors
132        .sar_amp_ctrl2()
133        .modify(|_, w| unsafe { w.sar_amp_wait3().bits(1) });
134}
135
136#[doc(hidden)]
137pub trait RegisterAccess {
138    fn set_attenuation(channel: usize, attenuation: u8);
139
140    fn clear_dig_force();
141
142    fn set_start_force();
143
144    fn set_en_pad_force();
145
146    fn set_en_pad(channel: u8);
147
148    fn clear_start_sample();
149
150    fn start_sample();
151
152    /// Returns whether sampling is done.
153    fn is_done() -> bool;
154
155    /// Reads sample data.
156    fn read_data() -> u16;
157
158    /// Configures the SAR clock divider.
159    ///
160    /// See `adc_ll_set_sar_clk_div` and `ADC_LL_SAR_CLK_DIV_DEFAULT`.
161    fn set_sar_clk_div();
162
163    /// Sets up ADC hardware for calibration.
164    fn calibration_init();
165
166    /// Sets calibration parameter to ADC hardware.
167    fn set_init_code(data: u16);
168
169    /// Resets flags.
170    fn reset();
171}
172
173impl RegisterAccess for crate::peripherals::ADC1<'_> {
174    fn set_attenuation(channel: usize, attenuation: u8) {
175        SENS::regs().sar_atten1().modify(|r, w| {
176            let new_value = (r.bits() & !(0b11 << (channel * 2)))
177                | (((attenuation & 0b11) as u32) << (channel * 2));
178
179            unsafe { w.sar1_atten().bits(new_value) }
180        });
181    }
182
183    fn clear_dig_force() {
184        SENS::regs()
185            .sar_meas1_mux()
186            .modify(|_, w| w.sar1_dig_force().clear_bit());
187    }
188
189    fn set_start_force() {
190        SENS::regs()
191            .sar_meas1_ctrl2()
192            .modify(|_, w| w.meas1_start_force().set_bit());
193    }
194
195    fn set_en_pad_force() {
196        SENS::regs()
197            .sar_meas1_ctrl2()
198            .modify(|_, w| w.sar1_en_pad_force().set_bit());
199    }
200
201    fn set_en_pad(channel: u8) {
202        SENS::regs()
203            .sar_meas1_ctrl2()
204            .modify(|_, w| unsafe { w.sar1_en_pad().bits(1 << channel) });
205    }
206
207    fn clear_start_sample() {
208        SENS::regs()
209            .sar_meas1_ctrl2()
210            .modify(|_, w| w.meas1_start_sar().clear_bit());
211    }
212
213    fn start_sample() {
214        // ADC1 must be idle before a new software trigger. See
215        // https://github.com/espressif/esp-idf/blob/8c750b0/components/hal/esp32s3/include/hal/adc_ll.h#L973
216        while meas1_busy() {}
217
218        SENS::regs()
219            .sar_meas1_ctrl2()
220            .modify(|_, w| w.meas1_start_sar().set_bit());
221    }
222
223    fn is_done() -> bool {
224        SENS::regs()
225            .sar_meas1_ctrl2()
226            .read()
227            .meas1_done_sar()
228            .bit_is_set()
229    }
230
231    fn read_data() -> u16 {
232        SENS::regs()
233            .sar_meas1_ctrl2()
234            .read()
235            .meas1_data_sar()
236            .bits()
237    }
238
239    fn set_sar_clk_div() {
240        SENS::regs().sar_reader1_ctrl().modify(|_, w| unsafe {
241            cfg_select! {
242                esp32s2 => w.sar1_clk_div().bits(1),
243                _ => w.sar_sar1_clk_div().bits(1),
244            }
245        });
246    }
247
248    fn calibration_init() {
249        // https://github.com/espressif/esp-idf/blob/800f141f94c0f880c162de476512e183df671307/components/hal/esp32s3/include/hal/adc_ll.h#L833
250        // https://github.com/espressif/esp-idf/blob/800f141f94c0f880c162de476512e183df671307/components/hal/esp32s2/include/hal/adc_ll.h#L1145
251        regi2c::ADC_SAR1_DREF.write_field(4);
252    }
253
254    fn set_init_code(data: u16) {
255        let [msb, lsb] = data.to_be_bytes();
256
257        regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(msb);
258        regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(lsb);
259    }
260
261    fn reset() {
262        let adc = APB_SARADC::regs();
263        let sensors = SENS::regs();
264
265        adc.int_clr().write(|w| w.adc1_done().clear_bit_by_one());
266        LPWR::regs()
267            .int_clr()
268            .write(|w| w.saradc1().clear_bit_by_one());
269
270        sensors
271            .sar_meas1_ctrl2()
272            .modify(|_, w| w.meas1_start_sar().clear_bit());
273    }
274}
275
276fn meas1_busy() -> bool {
277    let status = SENS::regs().sar_slave_addr1().read();
278    cfg_select! {
279        esp32s3 => status.sar_saradc_meas_status().bits() != 0,
280        _ => status.meas_status().bits() != 0,
281    }
282}
283
284impl super::CalibrationAccess for crate::peripherals::ADC1<'_> {
285    const ADC_VAL_MASK: u16 = ADC_VAL_MASK;
286
287    fn enable_vdef(enable: bool) {
288        regi2c::ADC_SAR1_DREF.write_field(enable as u8);
289    }
290
291    fn connect_gnd(enable: bool) {
292        regi2c::ADC_SAR1_ENCAL_GND.write_field(enable as u8);
293    }
294
295    fn setup_calibration(atten: Attenuation) {
296        // With no pad selected the hardware falls back to channel 0's attenuation, so
297        // that is where `cal_setup` programs it.
298        SENS::regs()
299            .sar_meas1_ctrl2()
300            .modify(|_, w| unsafe { w.sar1_en_pad().bits(0) });
301        Self::set_attenuation(0, atten as u8);
302    }
303}
304
305impl RegisterAccess for crate::peripherals::ADC2<'_> {
306    fn set_attenuation(channel: usize, attenuation: u8) {
307        SENS::regs().sar_atten2().modify(|r, w| {
308            let new_value = (r.bits() & !(0b11 << (channel * 2)))
309                | (((attenuation & 0b11) as u32) << (channel * 2));
310
311            unsafe { w.sar2_atten().bits(new_value) }
312        });
313    }
314
315    fn clear_dig_force() {
316        SENS::regs()
317            .sar_meas2_mux()
318            .modify(|_, w| w.sar2_rtc_force().set_bit());
319
320        APB_SARADC::regs()
321            .arb_ctrl()
322            .modify(|_, w| w.rtc_force().set_bit());
323    }
324
325    fn set_start_force() {
326        SENS::regs()
327            .sar_meas2_ctrl2()
328            .modify(|_, w| w.meas2_start_force().set_bit());
329    }
330
331    fn set_en_pad_force() {
332        SENS::regs()
333            .sar_meas2_ctrl2()
334            .modify(|_, w| w.sar2_en_pad_force().set_bit());
335    }
336
337    fn set_en_pad(channel: u8) {
338        SENS::regs()
339            .sar_meas2_ctrl2()
340            .modify(|_, w| unsafe { w.sar2_en_pad().bits(1 << channel) });
341    }
342
343    fn clear_start_sample() {
344        SENS::regs()
345            .sar_meas2_ctrl2()
346            .modify(|_, w| w.meas2_start_sar().clear_bit());
347    }
348
349    fn start_sample() {
350        SENS::regs()
351            .sar_meas2_ctrl2()
352            .modify(|_, w| w.meas2_start_sar().set_bit());
353    }
354
355    fn is_done() -> bool {
356        SENS::regs()
357            .sar_meas2_ctrl2()
358            .read()
359            .meas2_done_sar()
360            .bit_is_set()
361    }
362
363    fn read_data() -> u16 {
364        SENS::regs()
365            .sar_meas2_ctrl2()
366            .read()
367            .meas2_data_sar()
368            .bits()
369    }
370
371    fn set_sar_clk_div() {
372        SENS::regs().sar_reader2_ctrl().modify(|_, w| unsafe {
373            cfg_select! {
374                esp32s2 => w.sar2_clk_div().bits(1),
375                _ => w.sar_sar2_clk_div().bits(1),
376            }
377        });
378    }
379
380    fn calibration_init() {
381        regi2c::ADC_SAR2_DREF.write_field(4);
382    }
383
384    fn set_init_code(data: u16) {
385        let [msb, lsb] = data.to_be_bytes();
386
387        regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(msb);
388        regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(lsb);
389    }
390
391    fn reset() {
392        let adc = APB_SARADC::regs();
393        let sensors = SENS::regs();
394
395        adc.int_clr().write(|w| w.adc2_done().clear_bit_by_one());
396        LPWR::regs()
397            .int_clr()
398            .write(|w| w.saradc2().clear_bit_by_one());
399
400        sensors
401            .sar_meas2_ctrl2()
402            .modify(|_, w| w.meas2_start_sar().clear_bit());
403    }
404}
405
406impl super::CalibrationAccess for crate::peripherals::ADC2<'_> {
407    const ADC_VAL_MASK: u16 = ADC_VAL_MASK;
408
409    fn enable_vdef(enable: bool) {
410        regi2c::ADC_SAR2_DREF.write_field(enable as u8);
411    }
412
413    fn connect_gnd(enable: bool) {
414        regi2c::ADC_SAR2_ENCAL_GND.write_field(enable as u8);
415    }
416
417    fn setup_calibration(atten: Attenuation) {
418        SENS::regs()
419            .sar_meas2_ctrl2()
420            .modify(|_, w| unsafe { w.sar2_en_pad().bits(0) });
421        Self::set_attenuation(0, atten as u8);
422    }
423}
424
425/// Analog-to-Digital Converter peripheral driver.
426pub struct Adc<'d, ADC, Dm: crate::DriverMode> {
427    _adc: ADC,
428    attenuations: [Option<Attenuation>; NUM_ATTENS],
429    /// Hardware calibration code per attenuation, indexed by [`Attenuation`].
430    init_codes: [u16; super::ATTENUATION_COUNT],
431    active_channel: Option<u8>,
432    _guard: GenericPeripheralGuard<{ Peripheral::ApbSarAdc as u8 }>,
433    _phantom: PhantomData<(Dm, &'d mut ())>,
434}
435
436impl<'d, ADCX> Adc<'d, ADCX, Blocking>
437where
438    ADCX: RegisterAccess + 'd,
439{
440    /// Creates a new ADC instance with the given configuration.
441    pub fn new(adc_instance: ADCX, config: AdcConfig<ADCX>) -> Result<Self, Error>
442    where
443        ADCX: super::AdcCalEfuse + super::CalibrationAccess,
444    {
445        let guard = GenericPeripheralGuard::new();
446
447        let attenuations = config.attenuations;
448
449        init_hardware::<ADCX>();
450
451        let init_codes = super::hw_init_codes::<ADCX>(&attenuations);
452
453        for (channel, attenuation) in attenuations.iter().enumerate() {
454            if let Some(attenuation) = attenuation {
455                ADCX::set_attenuation(channel, *attenuation as u8);
456            }
457        }
458
459        // The bootloader runs conversions of its own to seed the RNG, so the done flag can
460        // already be set here and would make the first read return a stale result.
461        ADCX::reset();
462
463        Ok(Adc {
464            _adc: adc_instance,
465            attenuations,
466            init_codes,
467            active_channel: None,
468            _guard: guard,
469            _phantom: PhantomData,
470        })
471    }
472
473    /// Reconfigures the ADC driver to operate in asynchronous mode.
474    pub fn into_async(mut self) -> Adc<'d, ADCX, Async> {
475        acquire_async_adc();
476        self.set_interrupt_handler(adc_interrupt_handler);
477
478        // Reset interrupt flags and the start bit so both ADC units start from a
479        // known state in async mode.
480        ADCX::reset();
481
482        Adc {
483            _adc: self._adc,
484            attenuations: self.attenuations,
485            init_codes: self.init_codes,
486            active_channel: self.active_channel,
487            _guard: self._guard,
488            _phantom: PhantomData,
489        }
490    }
491
492    /// Starts and waits for a conversion on the specified pin and returns the
493    /// result.
494    ///
495    /// # Errors
496    ///
497    /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in
498    /// [`AdcConfig`].
499    pub fn read_blocking<PIN, CS>(&mut self, pin: &mut AdcPin<PIN, ADCX, CS>) -> Result<u16, Error>
500    where
501        PIN: AdcChannel,
502        CS: AdcCalScheme<ADCX>,
503    {
504        self.start_sample(pin)?;
505
506        // Wait for ADC to finish conversion
507        while !ADCX::is_done() {}
508
509        // Get converted value
510        let converted_value = ADCX::read_data();
511        ADCX::reset();
512
513        // Postprocess converted value according to calibration scheme used for pin
514        Ok(pin.cal_scheme.adc_val(converted_value))
515    }
516
517    /// Requests that the ADC begin a conversion on the specified pin.
518    ///
519    /// Takes an [`AdcPin`](super::AdcPin) reference, as it is
520    /// expected that the ADC will be able to sample whatever channel
521    /// underlies the pin.
522    ///
523    /// # Errors
524    ///
525    /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in
526    /// [`AdcConfig`].
527    pub fn read_oneshot<PIN, CS>(
528        &mut self,
529        pin: &mut super::AdcPin<PIN, ADCX, CS>,
530    ) -> nb::Result<u16, Error>
531    where
532        PIN: super::AdcChannel,
533        CS: super::AdcCalScheme<ADCX>,
534    {
535        if let Some(active_channel) = self.active_channel {
536            // There is conversion in progress:
537            // - if it's for a different channel try again later
538            // - if it's for the given channel, go ahead and check progress
539            if active_channel != pin.pin.adc_channel() {
540                return Err(nb::Error::WouldBlock);
541            }
542        } else {
543            // If no conversions are in progress, start a new one for given channel
544            self.start_sample(pin).map_err(nb::Error::Other)?;
545            self.active_channel = Some(pin.pin.adc_channel());
546        }
547
548        // Wait for ADC to finish conversion
549        let conversion_finished = ADCX::is_done();
550        if !conversion_finished {
551            return Err(nb::Error::WouldBlock);
552        }
553
554        // Get converted value
555        let converted_value = ADCX::read_data();
556        ADCX::reset();
557
558        // Postprocess converted value according to calibration scheme used for pin
559        let converted_value = pin.cal_scheme.adc_val(converted_value);
560
561        // Mark that no conversions are currently in progress
562        self.active_channel = None;
563
564        Ok(converted_value)
565    }
566}
567
568fn adc_interrupt_sources() -> [Interrupt; 2] {
569    // Oneshot conversion uses the RTC SAR controller. Completion is signalled on
570    // RTC_CORE (`RTC_CNTL` SARADCn). APB_ADC is bound as well for the digital
571    // `APB_SARADC_ADCn_DONE` bits.
572    [Interrupt::APB_ADC, Interrupt::RTC_CORE]
573}
574
575impl<ADCX> crate::private::Sealed for Adc<'_, ADCX, Blocking> {}
576
577impl<ADCX> InterruptConfigurable for Adc<'_, ADCX, Blocking> {
578    fn set_interrupt_handler(&mut self, handler: InterruptHandler) {
579        for interrupt in adc_interrupt_sources() {
580            for core in crate::system::Cpu::other() {
581                crate::interrupt::disable(core, interrupt);
582            }
583            crate::interrupt::bind_handler(interrupt, handler);
584        }
585    }
586}
587
588impl<'d, ADCX, Dm> Adc<'d, ADCX, Dm>
589where
590    ADCX: RegisterAccess + 'd,
591    Dm: crate::DriverMode,
592{
593    fn start_sample<PIN, CS>(&mut self, pin: &mut AdcPin<PIN, ADCX, CS>) -> Result<(), Error>
594    where
595        PIN: AdcChannel,
596        CS: AdcCalScheme<ADCX>,
597    {
598        let channel = pin.pin.adc_channel();
599        let attenuation = super::channel_attenuation(&self.attenuations, channel)?;
600
601        // Reprogrammed for every conversion: the regi2c block is shared with the PHY,
602        // so the code cannot be assumed to survive between reads.
603        ADCX::calibration_init();
604        ADCX::set_init_code(self.init_codes[attenuation as usize]);
605
606        ADCX::set_en_pad(channel);
607
608        ADCX::clear_start_sample();
609        ADCX::start_sample();
610
611        Ok(())
612    }
613}
614
615impl<'d, ADCX> Adc<'d, ADCX, Async>
616where
617    ADCX: RegisterAccess + 'd,
618{
619    /// Reconfigures the ADC driver to operate in [`Blocking`] mode.
620    pub fn into_blocking(self) -> Adc<'d, ADCX, Blocking> {
621        if release_async_adc() {
622            // Disable ADC interrupt on all cores if the last async ADC instance is disabled
623            for interrupt in adc_interrupt_sources() {
624                for cpu in crate::system::Cpu::all() {
625                    crate::interrupt::disable(cpu, interrupt);
626                }
627            }
628        }
629        Adc {
630            _adc: self._adc,
631            attenuations: self.attenuations,
632            init_codes: self.init_codes,
633            active_channel: self.active_channel,
634            _guard: self._guard,
635            _phantom: PhantomData,
636        }
637    }
638
639    /// Starts a conversion on the specified pin and waits until it completes.
640    ///
641    /// Takes an [`AdcPin`] reference, as it is expected that the
642    /// ADC will be able to sample whatever channel underlies the pin.
643    ///
644    /// # Errors
645    ///
646    /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in
647    /// [`AdcConfig`].
648    pub async fn read_oneshot<PIN, CS>(
649        &mut self,
650        pin: &mut AdcPin<PIN, ADCX, CS>,
651    ) -> Result<u16, Error>
652    where
653        ADCX: Instance,
654        PIN: AdcChannel,
655        CS: AdcCalScheme<ADCX>,
656    {
657        self.start_sample(pin)?;
658
659        AdcFuture::new(self).await;
660
661        let converted_value = ADCX::read_data();
662        ADCX::reset();
663
664        Ok(pin.cal_scheme.adc_val(converted_value))
665    }
666}
667
668static ASYNC_ADC_COUNT: AtomicU32 = AtomicU32::new(0);
669
670fn acquire_async_adc() {
671    ASYNC_ADC_COUNT.fetch_add(1, Ordering::Relaxed);
672}
673
674fn release_async_adc() -> bool {
675    ASYNC_ADC_COUNT.fetch_sub(1, Ordering::Relaxed) == 1
676}
677
678#[handler]
679#[ram]
680fn adc_interrupt_handler() {
681    let apb_status = APB_SARADC::regs().int_st().read();
682    let rtc_status = LPWR::regs().int_st().read();
683
684    if apb_status.adc1_done().bit_is_set() || rtc_status.saradc1().bit_is_set() {
685        unsafe { handle_async(crate::peripherals::ADC1::steal()) }
686    }
687
688    if apb_status.adc2_done().bit_is_set() || rtc_status.saradc2().bit_is_set() {
689        unsafe { handle_async(crate::peripherals::ADC2::steal()) }
690    }
691}
692
693fn handle_async<ADCX: Instance>(_instance: ADCX) {
694    ADCX::clear_interrupt();
695    ADCX::unlisten();
696    ADCX::waker().wake();
697}
698
699/// Enables asynchronous access.
700pub trait Instance: crate::private::Sealed {
701    /// Enables the ADC interrupt.
702    fn listen();
703
704    /// Disables the ADC interrupt.
705    fn unlisten();
706
707    /// Clears the ADC interrupt.
708    fn clear_interrupt();
709
710    /// Obtains the waker for the ADC interrupt.
711    fn waker() -> &'static AtomicWaker;
712}
713
714impl Instance for crate::peripherals::ADC1<'_> {
715    fn listen() {
716        APB_SARADC::regs()
717            .int_ena()
718            .modify(|_, w| w.adc1_done().set_bit());
719
720        SENS::regs().sar_reader1_ctrl().modify(|_, w| {
721            cfg_select! {
722                esp32s3 => w.sar_sar1_int_en().set_bit(),
723                _ => w.sar1_int_en().set_bit(),
724            }
725        });
726
727        LPWR::regs().int_ena().modify(|_, w| w.saradc1().set_bit());
728    }
729
730    fn unlisten() {
731        APB_SARADC::regs()
732            .int_ena()
733            .modify(|_, w| w.adc1_done().clear_bit());
734
735        SENS::regs().sar_reader1_ctrl().modify(|_, w| {
736            cfg_select! {
737                esp32s3 => w.sar_sar1_int_en().clear_bit(),
738                _ => w.sar1_int_en().clear_bit(),
739            }
740        });
741
742        LPWR::regs()
743            .int_ena()
744            .modify(|_, w| w.saradc1().clear_bit());
745    }
746
747    fn clear_interrupt() {
748        APB_SARADC::regs()
749            .int_clr()
750            .write(|w| w.adc1_done().clear_bit_by_one());
751        LPWR::regs()
752            .int_clr()
753            .write(|w| w.saradc1().clear_bit_by_one());
754    }
755
756    fn waker() -> &'static AtomicWaker {
757        static WAKER: AtomicWaker = AtomicWaker::new();
758
759        &WAKER
760    }
761}
762
763impl Instance for crate::peripherals::ADC2<'_> {
764    fn listen() {
765        APB_SARADC::regs()
766            .int_ena()
767            .modify(|_, w| w.adc2_done().set_bit());
768
769        SENS::regs().sar_reader2_ctrl().modify(|_, w| {
770            cfg_select! {
771                esp32s3 => w.sar_sar2_int_en().set_bit(),
772                _ => w.sar2_int_en().set_bit(),
773            }
774        });
775
776        LPWR::regs().int_ena().modify(|_, w| w.saradc2().set_bit());
777    }
778
779    fn unlisten() {
780        APB_SARADC::regs()
781            .int_ena()
782            .modify(|_, w| w.adc2_done().clear_bit());
783
784        SENS::regs().sar_reader2_ctrl().modify(|_, w| {
785            cfg_select! {
786                esp32s3 => w.sar_sar2_int_en().clear_bit(),
787                _ => w.sar2_int_en().clear_bit(),
788            }
789        });
790
791        LPWR::regs()
792            .int_ena()
793            .modify(|_, w| w.saradc2().clear_bit());
794    }
795
796    fn clear_interrupt() {
797        APB_SARADC::regs()
798            .int_clr()
799            .write(|w| w.adc2_done().clear_bit_by_one());
800        LPWR::regs()
801            .int_clr()
802            .write(|w| w.saradc2().clear_bit_by_one());
803    }
804
805    fn waker() -> &'static AtomicWaker {
806        static WAKER: AtomicWaker = AtomicWaker::new();
807
808        &WAKER
809    }
810}
811
812#[must_use = "futures do nothing unless you `.await` or poll them"]
813struct AdcFuture<ADCX: Instance> {
814    phantom: PhantomData<ADCX>,
815    _wake_lock: WakeLock,
816}
817
818impl<ADCX: Instance> AdcFuture<ADCX> {
819    fn new(_self: &Adc<'_, ADCX, Async>) -> Self {
820        ADCX::listen();
821        Self {
822            phantom: PhantomData,
823            _wake_lock: WakeLock::new(),
824        }
825    }
826}
827
828impl<ADCX: Instance + RegisterAccess> core::future::Future for AdcFuture<ADCX> {
829    type Output = ();
830
831    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
832        ADCX::waker().register(cx.waker());
833        if ADCX::is_done() {
834            ADCX::clear_interrupt();
835            Poll::Ready(())
836        } else {
837            Poll::Pending
838        }
839    }
840}
841
842impl<ADCX: Instance> Drop for AdcFuture<ADCX> {
843    fn drop(&mut self) {
844        ADCX::unlisten();
845    }
846}
847
848impl super::AdcCalEfuse for crate::peripherals::ADC1<'_> {
849    fn init_code(atten: Attenuation) -> Option<u16> {
850        crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC1, atten)
851    }
852
853    fn cal_mv(atten: Attenuation) -> Option<u16> {
854        crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC1, atten)
855    }
856
857    fn cal_code(atten: Attenuation) -> Option<u16> {
858        crate::efuse::rtc_calib_cal_code(AdcCalibUnit::ADC1, atten)
859    }
860}
861
862impl super::AdcCalEfuse for crate::peripherals::ADC2<'_> {
863    fn init_code(atten: Attenuation) -> Option<u16> {
864        crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC2, atten)
865    }
866
867    fn cal_mv(atten: Attenuation) -> Option<u16> {
868        crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC2, atten)
869    }
870
871    fn cal_code(atten: Attenuation) -> Option<u16> {
872        crate::efuse::rtc_calib_cal_code(AdcCalibUnit::ADC2, atten)
873    }
874}