Skip to main content

esp_hal/analog/adc/calibration/
basic.rs

1use core::marker::PhantomData;
2
3use crate::analog::adc::{
4    AdcCalEfuse,
5    AdcCalScheme,
6    AdcCalSource,
7    AdcConfig,
8    Attenuation,
9    CalibrationAccess,
10};
11
12/// Basic ADC calibration scheme
13///
14/// Basic calibration sets the initial ADC bias value so that a zero voltage
15/// gives a reading of zero. The correct bias value is usually stored in efuse,
16/// but can also be measured at runtime by connecting the ADC input to ground
17/// internally.
18///
19/// Failing to apply basic calibration can substantially reduce the ADC's output
20/// range because bias correction is done *before* the ADC's output is truncated
21/// to 12 bits.
22#[derive(Clone, Copy)]
23pub struct AdcCalBasic<ADCI> {
24    /// Calibration value to set to ADC unit
25    cal_val: u16,
26
27    #[cfg(esp32c5)]
28    chan_compens: i32,
29
30    _phantom: PhantomData<ADCI>,
31}
32
33impl<ADCI> crate::private::Sealed for AdcCalBasic<ADCI> {}
34
35impl<ADCI> AdcCalScheme<ADCI> for AdcCalBasic<ADCI>
36where
37    ADCI: AdcCalEfuse + CalibrationAccess,
38{
39    fn new_cal(atten: Attenuation) -> Self {
40        // Try to get init code (Dout0) from efuse
41        // Dout0 means mean raw ADC value when zero voltage applied to input.
42        let cal_val = ADCI::init_code(atten).unwrap_or_else(|| {
43            // As a fallback try to calibrate via connecting input to ground internally.
44            AdcConfig::<ADCI>::adc_calibrate(atten, AdcCalSource::Gnd)
45        });
46
47        #[cfg(esp32c5)]
48        let chan_compens = ADCI::cal_chan_compens(atten, ADCI::ADC_CAL_CHANNEL).unwrap_or(0);
49
50        Self {
51            cal_val,
52            #[cfg(esp32c5)]
53            chan_compens,
54            _phantom: PhantomData,
55        }
56    }
57
58    fn adc_cal(&self) -> u16 {
59        self.cal_val
60    }
61
62    // This is default from the trait for other target than esp32c5
63    #[cfg(esp32c5)]
64    fn adc_val(&self, val: u16) -> u16 {
65        val.saturating_sub(self.chan_compens as u16)
66            .clamp(0, ADCI::ADC_VAL_MASK)
67    }
68}