ADC
About
ADC (analog to digital converter) is a very common peripheral used to convert an analog signal such as voltage to a digital form so that it can be read and processed by a microcontroller.
ADCs are very useful in control and monitoring applications since most sensors (e.g., temperature, pressure, force) produce analog output voltages.
Note
Each SoC or module has a different number of ADCs with a different number of channels and pins available. Refer to the datasheet of each board for more info.
Arduino-ESP32 ADC API
ADC OneShot mode
The ADC OneShot mode API is fully compatible with Arduino’s analogRead function.
When you call the analogRead or analogReadMilliVolts function, it returns the result of a single conversion on the requested pin.
Note
On ESP32-S31 analogRead logs an error and returns 0. The sample does not fit in a 16-bit linear code. Use analogReadComparator for the raw sample, or analogReadMilliVolts for the voltage.
analogRead
This function is used to get the ADC raw value for a given pin/ADC channel. On ESP32-S31 it logs an error and returns 0.
uint16_t analogRead(uint8_t pin);
pinGPIO pin to read analog value
This function will return analog raw value (non-calibrated).
analogReadComparator
This function is available on ESP32-S31 only. It returns the full 17-bit comparator vector (0 to 131071).
uint32_t analogReadComparator(uint8_t pin);
pinGPIO pin to read the comparator vector
The result is not a linear code: 0 V is not raw 0, and even and odd channels run in opposite directions. Use analogReadMilliVolts for the voltage.
analogReadMilliVolts
This function is used to get the ADC raw value for a given pin/ADC channel and convert it to a calibrated result in millivolts.
int32_t analogReadMilliVolts(uint8_t pin);
pinGPIO pin to read analog value
This function will return an analog value in millivolts (calibrated). The result is signed, so a voltage below 0 V stays negative.
Note
On ESP32-S31 the calibrated result covers about -2000 mV to +2000 mV. A pin tied to GND reads about 0 mV. Voltages above +2000 mV clip.
analogReadResolution
This function is used to set the resolution of an analogRead return value. The default is 12 bits (range from 0 to 4095).
When a different resolution is set, the values read will be shifted to match the given resolution.
Note
For ESP32-S2 chip revision v0.0, the default ADC resolution is 13 bits (0-8191) due to the ADC-112 errata. This is fixed in later revisions (v1.0+), which use the standard 12-bit resolution.
Note
On ESP32-S31 analogReadResolution is not supported and logs an error. analogReadComparator always returns the full 17-bit vector. Shifting that vector would corrupt the sample.
Range is 1 - 16. The default value will be used, if this function is not used.
Note
For the ESP32, the resolution is between 9 to 12 and it will change the ADC hardware resolution. Else the value will be shifted.
void analogReadResolution(uint8_t bits);
bitssets analog read resolution
analogSetAttenuation
This function is used to set the attenuation for all channels.
Input voltages can be attenuated before being input to the ADCs. There are 4 available attenuation options; the higher the attenuation is, the higher the measurable input voltage could be.
ESP32-S31 has a single attenuation option, ADC_11db. The name matches the other chips. Electrically it is 0 dB (ADC_ATTEN_DB_0), with a calibrated range of about -2000 mV to +2000 mV. analogSetAttenuation and analogSetPinAttenuation are not supported and log an error.
The measurable input voltage differs for each chip. See the table below for detailed information.
Attenuation |
Measurable input voltage range |
|---|---|
|
100 mV ~ 950 mV |
|
100 mV ~ 1250 mV |
|
150 mV ~ 1750 mV |
|
150 mV ~ 3100 mV |
Attenuation |
Measurable input voltage range |
|---|---|
|
0 mV ~ 750 mV |
|
0 mV ~ 1050 mV |
|
0 mV ~ 1300 mV |
|
0 mV ~ 2500 mV |
Attenuation |
Measurable input voltage range |
|---|---|
|
0 mV ~ 750 mV |
|
0 mV ~ 1050 mV |
|
0 mV ~ 1300 mV |
|
0 mV ~ 2500 mV |
Attenuation |
Measurable input voltage range |
|---|---|
|
0 mV ~ 950 mV |
|
0 mV ~ 1250 mV |
|
0 mV ~ 1750 mV |
|
0 mV ~ 3100 mV |
Attenuation |
Measurable input voltage range |
|---|---|
|
-2000 mV ~ 2000 mV |
void analogSetAttenuation(adc_attenuation_t attenuation);
attenuationsets the attenuation.
analogSetPinAttenuation
This function is used to set the attenuation for a specific pin/ADC channel. For more information refer to analogSetAttenuation.
void analogSetPinAttenuation(uint8_t pin, adc_attenuation_t attenuation);
pinselects the specific pin for attenuation settings.attenuationsets the attenuation.
analogSetWidth
Note
This function is only available for ESP32 chip.
This function is used to set the hardware sample bits and read resolution. Default is 12 bits (0 - 4095). Range is 9 - 12.
void analogSetWidth(uint8_t bits);
ADC Continuous mode
ADC Continuous mode is an API designed for performing analog conversions on multiple pins in the background, with the feature of receiving a callback upon completion of these conversions to access the results.
This API allows you to specify the desired number of conversions per pin within a single cycle, along with its corresponding sampling rate.
The outcome of the analogContinuousRead function is an array of adc_continuous_result_t structures.
These structures hold both the raw average value and the average value in millivolts for each pin.
Note
On ESP32-S31 the raw field is the last comparator-vector sample. Each sample is calibrated on its own, and avg_read_mvolts is the average of those millivolt results. Averaging the raw vectors would not be the voltage of the average.
analogContinuous
This function is used to configure ADC continuous peripheral on selected pins.
bool analogContinuous(const uint8_t pins[], size_t pins_count, uint32_t conversions_per_pin, uint32_t sampling_freq_hz, void (*userFunc)(void));
pins[]array of pins to be set uppins_countcount of pins in arrayconversions_per_pinsets how many conversions per pin will run each ADC cyclesampling_freq_hzsets sampling frequency of ADC in HzuserFuncsets callback function to be called after adc conversion is done (can be set toNULL)
This function will return true if configuration is successful.
If false is returned, error occurs and ADC continuous was not configured.
analogContinuousRead
This function is used to read ADC continuous data to the result buffer. The result buffer is an array of adc_continuous_result_t.
typedef struct {
uint8_t pin; /*!<ADC pin */
uint8_t channel; /*!<ADC channel */
int avg_read_raw; /*!<ADC average raw data */
int avg_read_mvolts; /*!<ADC average voltage in mV */
} adc_continuous_result_t;
bool analogContinuousRead(adc_continuous_result_t ** buffer, uint32_t timeout_ms);
bufferconversion result buffer to read from ADC in adc_continuous_result_t format.timeout_mstime to wait for data in milliseconds.
This function will return true if reading is successful and buffer is filled with data.
If false is returned, reading has failed and buffer is set to NULL.
analogContinuousStart
This function is used to start ADC continuous conversions.
bool analogContinuousStart();
This function will return true if ADC continuous is successfully started.
If false is returned, starting ADC continuous has failed.
analogContinuousStop
This function is used to stop ADC continuous conversions.
bool analogContinuousStop();
This function will return true if ADC continuous is successfully stopped.
If false is returned, stopping ADC continuous has failed.
analogContinuousDeinit
This function is used to deinitialize ADC continuous peripheral.
bool analogContinuousDeinit();
This function will return true if ADC continuous is successfully deinitialized.
If false is returned, deinitilization of ADC continuous has failed.
analogContinuousSetAtten
This function is used to set the attenuation for ADC continuous peripheral. For more information refer to analogSetAttenuation.
void analogContinuousSetAtten(adc_attenuation_t attenuation);
attenuationsets the attenuation (default isADC_11db).
Note
On ESP32-S31, analogContinuousSetAtten is not supported and logs an error. The only range is already active: ADC_11db, 0 dB, about -2000 mV to +2000 mV. See analogSetAttenuation.
analogContinuousSetWidth
This function is used to set the hardware resolution bits. Default value is 12 bits (0 - 4095), except on ESP32-S31 where it is fixed at 17 bits.
Note
On ESP32, the supported range is 9 to 12 bits. On ESP32-S31 analogContinuousSetWidth is not supported and logs an error. The width stays at 17 bits.
void analogContinuousSetWidth(uint8_t bits);
bitssets resolution bits.
Example Applications
Here is an example of how to use the ADC in OneShot mode or you can run Arduino example 01.Basics -> AnalogReadSerial.
#include <Arduino.h>
void setup() {
// initialize serial communication at 115200 bits per second:
Serial.begin(115200);
// Set the resolution to 12 bits (0-4095). Not used on ESP32-S31.
#ifndef CONFIG_IDF_TARGET_ESP32S31
analogReadResolution(12);
#endif
}
void loop() {
// A0 GPIO: ESP32 36, S2/S3/C2/C5/H2 1, C3/C6/C61 0, S31 42, P4 16.
const uint8_t adc_pin = A0;
#ifdef CONFIG_IDF_TARGET_ESP32S31
uint32_t analogValue = analogReadComparator(adc_pin);
#else
uint32_t analogValue = analogRead(adc_pin);
#endif
int32_t analogVolts = analogReadMilliVolts(adc_pin);
// print out the values you read:
Serial.printf("ADC analog value = %" PRIu32 "\n", analogValue);
Serial.printf("ADC millivolts value = %" PRId32 "\n", analogVolts);
delay(100); // delay in between reads for clear read from serial
}
Here is an example of how to use the ADC in Continuous mode.
#include <Arduino.h>
// Define how many conversion per pin will happen and reading the data will be and average of all conversions
#define CONVERSIONS_PER_PIN 5
// Declare array of ADC pins that will be used for ADC Continuous mode - ONLY ADC1 pins are supported
// Number of selected pins can be from 1 to ALL ADC1 pins.
#ifdef CONFIG_IDF_TARGET_ESP32
uint8_t adc_pins[] = {36, 39, 34, 35}; //some of ADC1 pins for ESP32
#elif CONFIG_IDF_TARGET_ESP32S31
uint8_t adc_pins[] = {42, 43, 44, 45}; //ADC1 pins for ESP32-S31
#else
uint8_t adc_pins[] = {1, 2, 3, 4}; //ADC1 common pins for ESP32S2/S3 + ESP32C3/C6 + ESP32H2
#endif
// Calculate how many pins are declared in the array - needed as input for the setup function of ADC Continuous
uint8_t adc_pins_count = sizeof(adc_pins) / sizeof(uint8_t);
// Flag which will be set in ISR when conversion is done
volatile bool adc_coversion_done = false;
// Result structure for ADC Continuous reading
adc_continuous_result_t *result = NULL;
// ISR Function that will be triggered when ADC conversion is done
void ARDUINO_ISR_ATTR adcComplete() {
adc_coversion_done = true;
}
void setup() {
// Initialize serial communication at 115200 bits per second:
Serial.begin(115200);
// Optional: resolution and attenuation. ESP32-S31 keeps its fixed defaults.
#if !defined(CONFIG_IDF_TARGET_ESP32S31)
analogContinuousSetWidth(12);
analogContinuousSetAtten(ADC_11db);
#endif
// Setup ADC Continuous with following input:
// array of pins, count of the pins, how many conversions per pin in one cycle will happen, sampling frequency, callback function
analogContinuous(adc_pins, adc_pins_count, CONVERSIONS_PER_PIN, 20000, &adcComplete);
// Start ADC Continuous conversions
analogContinuousStart();
}
void loop() {
// Check if conversion is done and try to read data
if (adc_coversion_done == true) {
// Set ISR flag back to false
adc_coversion_done = false;
// Read data from ADC
if (analogContinuousRead(&result, 0)) {
// Optional: Stop ADC Continuous conversions to have more time to process (print) the data
analogContinuousStop();
for (int i = 0; i < adc_pins_count; i++) {
Serial.printf("\nADC PIN %u data:", result[i].pin);
Serial.printf("\n Avg raw value = %d", result[i].avg_read_raw);
Serial.printf("\n Avg millivolts value = %d", result[i].avg_read_mvolts);
}
// Delay for better readability of ADC data
delay(1000);
// Optional: If ADC was stopped, start ADC conversions and wait for callback function to set adc_coversion_done flag to true
analogContinuousStart();
} else {
Serial.println("Error occurred during reading data. Set Core Debug Level to error or lower for more information.");
}
}
}