The world around us is analog. Let’s learn how to do analog input readings with ESP32, using built-in functions. The Arduino code is ready to harness all the power necessary.
This microcontroller in specific for this article (Xiao ESP32-C6 – for my dev board), is capable of reading analog values up to 12bit and 3.3V. It means reading 4096 steps, or 805uV per step. That is different from the Arduino UNO for example, that can read values up to 5V in 10bit only.
The circuit
Our board with the ESP32-C6 features three analog input, A0-A2 located in the first three pins of the PCB. I am connecting a 10k Ohm potentiometer to pin A0, as seen in the image below.
You could obviously connect virtually any analog signal to any of the three inputs, giving you condition the signal good enough. It means generally to limit it to 3.3V and ground it in the same GND as the board.
The code
I got the code below from this source, the official SeeedStudio Xiao ESP32-C6 page.
const int analogPin = A0;
void setup() {
// Initialize serial communication at 115200 bits per second
Serial.begin(115200);
// Set the resolution to 12 bits (0-4095)
analogReadResolution(12);
//analogSetWidth(12);
}
void loop() {
// Read the analog value and millivolts for the analogPin
int analogValue = analogRead(analogPin);
int analogVolts = analogReadMilliVolts(analogPin);
// Print the values to the Serial Monitor
Serial.printf("ADC analog value = %d\n", analogValue);
Serial.printf("ADC millivolts value = %d\n", analogVolts);
delay(100); // Delay for clear reading from serial
}
Notice that I use “analogReadResolution(12)”, meaning the resolution for the input is 12bit. I have done below some testing with 10bit to show you the difference. Notice that it is supposed to go from 0 to 1023, what it roughly does.
Final words
Analog input are the way a microcontroller can “listen” to the external world, which is analog. Learn how to harness all its power is crucial to anyone developing embedded systems.
With all that said, see you next time. Take care and be safe everyone.
Leave a Reply