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 analogue output voltages.
Note
Each SoC or module has a different number of ADC’s with a different number of channels and pins available. Refer to 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.
analogRead
This function is used to get the ADC raw value for a given pin/ADC channel.
uint16_t analogRead(uint8_t pin);
pin
GPIO pin to read analog value
This function will return analog raw value (non-calibrated).
analogReadMillivolts
This function is used to get ADC raw value for a given pin/ADC channel and convert it to calibrated result in millivolts.
uint32_t analogReadMilliVolts(uint8_t pin);
pin
GPIO pin to read analog value
This function will return analog value in millivolts (calibrated).
analogReadResolution
This function is used to set the resolution of analogRead
return value. Default is 12 bits (range from 0 to 4095)
for all chips except ESP32S3 where default is 13 bits (range from 0 to 8191).
When different resolution is set, the values read will be shifted to match the given resolution.
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 to12 and it will change the ADC hardware resolution. Else value will be shifted.
void analogReadResolution(uint8_t bits);
bits
sets 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.
The measurable input voltage differs for each chip, see 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 |
void analogSetAttenuation(adc_attenuation_t attenuation);
attenuation
sets 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);
pin
selects specific pin for attenuation settings.attenuation
sets 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 12bit (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_data_t
structures.
These structures hold both the raw average value and the average value in millivolts for each pin.
analogContinuous
This function is used to configure ADC continuous peripheral on selected pins.
bool analogContinuous(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_count
count of pins in arrayconversions_per_pin
sets how many conversions per pin will run each ADC cyclesampling_freq_hz
sets sampling frequency of ADC in HzuserFunc
sets 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_continuos_data_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_continuos_data_t;
bool analogContinuousRead(adc_continuos_data_t ** buffer, uint32_t timeout_ms);
buffer
conversion result buffer to read from ADC in adc_continuos_data_t format.timeout_ms
time 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 succesfully 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 succesfully 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 succesfully 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 informations refer to analogSetAttenuation.
void analogContinuousSetAtten(adc_attenuation_t attenuation);
attenuation
sets the attenuation (default is 11db).
analogContinuousSetWidth
This function is used to set the hardware resolution bits. Default value for all chips is 12bit (0 - 4095).
Note
This function will take effect only for ESP32 chip, as it allows to set resolution in range 9-12 bits.
void analogContinuousSetWidth(uint8_t bits);
bits
sets 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.
void setup() {
// initialize serial communication at 115200 bits per second:
Serial.begin(115200);
//set the resolution to 12 bits (0-4096)
analogReadResolution(12);
}
void loop() {
// read the analog / millivolts value for pin 2:
int analogValue = analogRead(2);
int analogVolts = analogReadMilliVolts(2);
// print out the values you read:
Serial.printf("ADC analog value = %d\n",analogValue);
Serial.printf("ADC millivolts value = %d\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.
// 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
#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_continuos_data_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 for ESP32: Set the resolution to 9-12 bits (default is 12 bits)
analogContinuousSetWidth(12);
// Optional: Set different attenaution (default is ADC_11db)
analogContinuousSetAtten(ADC_11db);
// 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 %d data:", result[i].pin);
Serial.printf("\n Avg raw value = %d", result[i].avg_read_raw);
Serial.printf("\n Avg milivolts 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 occured during reading data. Set Core Debug Level to error or lower for more informations.");
}
}
}