An analog to digital converter is a device that detects the voltage level on a pin of a microcontroller and then converts that to a numerical value. The ESP32 has two ADC's with multiple channels exposed upon its pins. Because each pin on the ESP332 has different peripherals attached to it, you may need to choose an ADC channel that doesn't clash with other devices in use.
If your project utilises Wi-Fi don't use and of ADC 2's channels still to ADC 1's channels.
The ADC's on an ESP32 can read a voltage between 0V and 3.3V and has 12 bit resolution, this means that the ADC will return a number between 0 and 4096 (212). The table below shows some expected ADC outputs:
Input V | ADC Output |
---|---|
0.0 | 0 |
0.825 | 1024 |
1.65 | 2048 |
3.3 | 4096 |
To access a ADC with our ESP32 we use the analogRead() command, this will return the ADC reading into a variable. We need to specify which ADC we need to read in (i.e. which pin our sensor is attached to). The ESP32 has multiple ADC channels that we can utilise, which are illustrated in the chart below. Please note that ADC1_CH1, ADC1_CH2, ADC2_CH1, and ADC2_CH6 are not connected to any pins on this device.
ADC | Channel | ADC_ID | GPI | ESP32 Pin |
---|---|---|---|---|
1 | 0 | ADC1_CH0 | 36 | L14 |
1 | 3 | ADC1_CH3 | 39 | L13 |
1 | 4 | ADC1_CH4 | 32 | L10 |
1 | 5 | ADC1_CH5 | 33 | L9 |
1 | 6 | ADC1_CH6 | 34 | L12 |
1 | 7 | ADC1_CH7 | 35 | L11 |
2 | 0 | ADC2_CH0 | 4 | R5 |
2 | 2 | ADC2_CH2 | 2 | R4 |
2 | 3 | ADC2_CH3 | 15 | R3 |
2 | 4 | ADC2_CH4 | 13 | L3 |
2 | 5 | ADC2_CH5 | 12 | L4 |
2 | 7 | ADC2_CH7 | 27 | L6 |
2 | 8 | ADC2_CH8 | 25 | L8 |
2 | 9 | ADC2_CH9 | 26 | L7 |
If we choose to use ADC1_CH, we can read it by using the following function call:
int adc_reading = analogRead(36);
and we need to connect our sensor to the ESP32's Left pin14.
We can use a formula to convert our ADC reading back to the voltage level for use in our program:
float voltage = (adc_reading/4096.0) * 3.3;
A complete C++ program file called main.cpp is illustrated below, you can download a link to the actual file here
// Dr Paul Lunn - Coventry University
// 18/06/2019
// ESP32 ADC Test
#include <Arduino.h>
const int SERIAL_0_SPEED = 115200;
// The setup() function is called once at the beginning of the program
void setup()
{
Serial.begin(SERIAL_0_SPEED); // begin serial link
Serial.println("ESP32 ADC Test"); // print text onto screen via serial link
}
// The loop() function runs over and over again forever
void loop()
{
int adc_reading = analogRead(36); // use adc to read current value
float voltage = (adc_reading / 4096.0) * 3.3; //convert adc to voltage level
// send results to serial link
Serial.print("ADC reading = ");
Serial.print(adc_reading);
Serial.print(" Input Voltage = ");
Serial.println(voltage);
delay(1000); // wait for a second
}