Experiment # 4: ESP32 ADC - Read Analog Values With Arduino IDE
Experiment # 4: ESP32 ADC - Read Analog Values With Arduino IDE
Experiment # 4: ESP32 ADC - Read Analog Values With Arduino IDE
Experiment 4
Experiment # 4:
ESP32 ADC – Read Analog Values with
Arduino IDE
Analog Inputs (ADC)
Reading an analog value with the ESP32 means you can measure varying
voltage levels between 0 V and 3.3 V.
ADC is Non-linear
Ideally, you would expect a linear behavior when using the ESP32 ADC pins.
However, that doesn’t happen. What you’ll get is a behavior as shown in the
following chart:
Embedded Systems Laboratory 2
Experiment 4
This behavior means that your ESP32 is not able to distinguish 3.3 V from 3.2
V. You’ll get the same value for both voltages: 4095.
The same happens for very low voltage values: for 0 V and 0.1 V you’ll get the
same value: 0. You need to keep this in mind when using the ESP32 ADC
pins.
analogRead() Function
Reading an analog input with the ESP32 using the Arduino IDE is as simple
as using the analogRead() function. It accepts as argument, the GPIO you
want to read:
analogRead(GPIO);
Embedded Systems Laboratory 3
Experiment 4
These analog input pins have 12-bit resolution. This means that when you
read an analog input, its range may vary from 0 to 4095.
Note: ADC2 pins cannot be used when Wi-Fi is used. So, if you’re using Wi-Fi and you’re having
trouble getting the value from an ADC2 GPIO, you may consider using an ADC1 GPIO instead, that should
solve your problem.
Embedded Systems Laboratory 4
Experiment 4
To see how everything ties together, we’ll make a simple example to read an
analog value from a potentiometer.
Schematic
Code
void setup() {
Serial.begin(115200);
delay(1000);
}
void loop() {
// Reading potentiometer value
potValue = analogRead(potPin);
Serial.println(potValue);
delay(500);
}
This code simply reads the values from the potentiometer and prints those
values in the Serial Monitor.
In the code, you start by defining the GPIO the potentiometer is connected to.
In this example, GPIO 34.
Serial.begin(115200);
In the loop(), use the analogRead()function to read the analog input from
the potPin.
potValue = analogRead(potPin);
Embedded Systems Laboratory 6
Experiment 4
Finally, print the values read from the potentiometer in the serial monitor.
Serial.println(potValue);
Upload the code provided to your ESP32. Make sure you have the right board
and COM port selected in the Tools menu.
After uploading the code and pressing the ESP32 reset button, open the
Serial Monitor at a baud rate of 115200. Rotate the potentiometer and see the
values changing.
The maximum value you’ll get is 4095 and the minimum value is 0.