🛠 Lire un capteur analogique : potentiomètre et ADC 10 bits
Objectives
Discover the 10-bit analog-to-digital converter (ADC) of the ATmega32u4: analogRead returns an integer from 0 to 1023 proportional to the voltage on the pin, between 0 V and 5 V. You will also learn about the peculiarity of the Leonardo's analog inputs: 12 inputs A0 to A11, where A6 to A11 are shared (multiplexed) with digital pins 4, 6, 8, 9, 10, and 12 — the Arduino core numbering is actually a source of confusion on these pins.
Hardware
- 1 Arduino Leonardo + micro-USB cable
- 1 potentiometer (10 kΩ typical)
- 3 wires: wiper to A0, one end to 5V, the other to GND
Complete code
const uint8_t POT_PIN = A0; // A0-A5 : broches analogiques « classiques »
void setup {
Serial.begin(9600); // Serial = USB CDC sur Leonardo
while (!Serial) { }
}
void loop {
int brut = analogRead(POT_PIN); // 0..1023 (ADC 10 bits)
float tension = brut * (5.0 / 1023.0); // tension approximative en volts
int pourcent = map(brut, 0, 1023, 0, 100);
Serial.print("brut="); Serial.print(brut);
Serial.print(" ~"); Serial.print(tension);
Serial.print(" V ("); Serial.print(pourcent); Serial.println(" %)");
delay(100);
}
Expected verification
When turning the potentiometer by hand, the displayed values follow: approximately 0 at one end stop, approximately 1023 at the other, and the calculated voltage remains between 0 and 5 V. If the value jumps significantly at rest, this is normal: an analog input not connected to a low-impedance source picks up noise.
Common errors
- Using A6-A11 without knowing they share digital pins 4/6/8/9/10/12: if you also use these pins digitally, the behavior becomes inconsistent (duplicate numbering in the core, see issue #187 of ArduinoCore-avr).
- Powering the sensor with 3V3: possible, but the measurement scale remains 0-5 V; an inconsistent reference skews the voltage calculation.
- Expecting 12-bit resolution: the ADC of the ATmega32u4 is 10 bits, not 12 as on an ESP32.
- Forgetting the common ground: a sensor powered by an external source must share GND with the board.
Other tutorials for this board
- Faire clignoter la LED intégrée (broche 13)
- Bouton et console série : Serial (USB) vs Serial1 (broches 0/1)
- Clavier USB : taper du texte avec la bibliothèque Keyboard
- Souris USB : déplacer le curseur avec la bibliothèque Mouse
- Asservir un servo moteur avec un potentiomètre (PWM)
- Programmer aux registres : interruption Timer/Counter1
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinoclavier-auto-tape.inoArduinosouris-cercle.inoArduinotelecommande-media.inoArduinobouton-clic-souris.inoArduino