Sensors and I/O
ADC analog sample
Battery voltage and analog sensors. Attenuation and calibration matter.
Sensors and I/O
Analog / battery
ESP32 family
Official path: examples/peripherals/adc
01 Overview
The ESP32 built-in ADC reads analog voltages, commonly used for battery monitoring and analog sensors like LDRs or potentiometers.
The official driver offers oneshot and continuous modes; the API changes across IDF versions, so check the matching docs.
Use for: resistor-divided battery voltage, general analog inputs where moderate accuracy is fine.
Avoid for: metrology-grade measurements (e.g., energy meters) – use an external ADC like ADS1115.
Input range depends on attenuation; default is 0-1.1V, so choose attenuation based on your signal amplitude.
Calibration compensates for manufacturing variance, but not all chips support it; detect at runtime.
02 Hardware
- GPIO voltage limit: Use a resistor divider to keep input below the GPIO maximum (about 3.3V) to avoid damage.
- Divider resistors: Battery voltage must be divided into the ADC range; resistor tolerance affects accuracy.
- Ground layout: Separate analog and digital grounds to prevent digital noise coupling, which shows up as jitter.
- Strapping pins: Avoid using strapping pins (e.g., GPIO0, GPIO12) as the only sample input because boot strapping can interfere.
- Filter capacitor: A small cap (e.g., 100nF) on the ADC pin filters high-frequency noise but increases settling time.
- Reference voltage: The internal reference drifts with temperature; calibration partially compensates.
03 Software flow
1. Select ADC channel and attenuation (e.g., ADC_ATTEN_DB_11 for 0-3.3V).
2. If supported, call the calibration API (e.g., esp_adc_cal) to get calibration coefficients.
3. Configure oneshot or continuous mode; continuous uses DMA for high-rate sampling.
4. Take multiple samples and average to reduce noise.
5. Convert raw values to voltage (accounting for divider ratio) and apply calibration curve.
6. Filter the voltage (e.g., moving average) for stable battery percentage display.
7. Low-battery detection: trigger shutdown or alarm when voltage drops below a threshold.
04 Core points
- The on-chip ADC is not a meter: accuracy is limited; don't use for high-precision measurements.
- Attenuation matters: different attenuation gives different ranges; choose to avoid clipping or poor resolution.
- Calibration is essential: without it, error can be large; enable in production.
- Sampling time: balance sample rate and filtering in continuous mode.
- Custom work: divider values, calibration curve, and low-battery shutdown thresholds must be tuned per product.