🛠 Première entrée analogique sur ADC1
Objectives
Read a voltage using the ESP32's analog-to-digital converter (ADC). We will deliberately use a channel from ADC1 (GPIO32 to GPIO39): ADC2 is unusable as soon as Wi-Fi is active — a classic pitfall that we will detail in the corresponding advanced tutorial. You will also discover the GPIO34-39 constraint: these pins are pure inputs, never outputs.
Hardware
- 1 ESP32 DevKit v1 board
- 1 10 kΩ potentiometer (pins connected to 3.3 V, GPIO34, GND)
- Optional: 100 nF capacitor between GPIO34 and GND
Complete code
const uint8_t POT_PIN = 34; // ADC1_CH6, entree seule
void setup {
Serial.begin(115200);
analogReadResolution(12); // 0..4095
analogSetPinAttenuation(POT_PIN, ADC_11db); // plage ~0 a 3,3 V
analogRead(POT_PIN); // 1er echantillon ignore
}
void loop {
uint32_t brut = analogRead(POT_PIN);
float mv = brut * 3300.0f / 4095.0f;
Serial.printf("ADC1 GPIO34 : %u -> %.0f mV\n", brut, mv);
delay(100);
}
Expected verification
When turning the potentiometer, the console displays a continuous value from 0 to 4095 and the corresponding voltage from 0 to approximately 3300 mV. At rest (finger near the wiper), the value may fluctuate by a few units: this is the normal noise of a 12-bit ADC without filtering.
Common errors
- Using GPIO2, 4, 12 to 15, or 17 to 19: these are ADC2 pins, which fail or return 0 as soon as Wi-Fi is running. It works without Wi-Fi, but never reuse this wiring in a connected product.
- Attempting a digitalWrite on GPIO34-39: these pins are input-only, with no internal pull-up resistor and no output capability.
- Forgetting analogSetPinAttenuation(ADC_11db): without it, the range is limited to ~1 V and the value will saturate.
- Measuring more than 3.3 V: the ESP32 is not 5 V tolerant on its analog inputs; use a voltage divider.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht22.inoArduinooled-i2c.inoArduinoserveur-web.inoArduino