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    _phantom: PhantomData<ADCI>,
28}
29
30impl<ADCI> crate::private::Sealed for AdcCalBasic<ADCI> {}
31
32impl<ADCI> AdcCalScheme<ADCI> for AdcCalBasic<ADCI>
33where
34    ADCI: AdcCalEfuse + CalibrationAccess,
35{
36    fn new_cal(atten: Attenuation) -> Self {
37        // Try to get init code (Dout0) from efuse
38        // Dout0 means mean raw ADC value when zero voltage applied to input.
39        let cal_val = ADCI::init_code(atten).unwrap_or_else(|| {
40            // As a fallback try to calibrate via connecting input to ground internally.
41            AdcConfig::<ADCI>::adc_calibrate(atten, AdcCalSource::Gnd)
42        });
43
44        Self {
45            cal_val,
46            _phantom: PhantomData,
47        }
48    }
49
50    fn adc_cal(&self) -> u16 {
51        self.cal_val
52    }
53}