🛠 Lire un capteur analogique avec l’ADC 10 bits
Objectives
Use the analog-to-digital converter of the ATmega2560: the Mega 2560 has 16 analog inputs (A0 to A15) with a 10-bit resolution, meaning integer values from 0 to 1023 for a default reference voltage of 5 V. You will learn how to read a sensor, convert the value to voltage, and understand the role of the AREF pin.
Hardware
- 1 × Arduino Mega 2560 + USB cable
- 1 × 10 kΩ potentiometer (simulating any analog sensor: LDR, flex sensor, etc.)
- Breadboard and jumper wires
Connect the two ends of the potentiometer to 5 V and GND, and the wiper (middle pin) to A0. The analog reference can be modified via the AREF pin and the analogReference function — never apply an external voltage to AREF without reading the documentation first.
Complete code
// Lecture ADC 10 bits — Arduino Mega 2560
const uint8_t CAPTEUR = A0; // 16 entrées : A0..A15
uint32_t t0 = 0;
void setup {
Serial.begin(115200);
}
void loop {
if (millis - t0 >= 100) { // 10 affichages / s
t0 = millis;
uint16_t brut = analogRead(CAPTEUR); // 0..1023
float tension = brut * (5.0 / 1023.0); // 0..5 V
Serial.print(F("brut=")); Serial.print(brut);
Serial.print(F(" tension=")); Serial.print(tension, 2);
Serial.println(F(" V"));
}
}
Expected verification
When turning the potentiometer, the raw value goes from 0 to 1023 and the voltage from 0.00 to 5.00 V in the serial monitor at 115200 bauds. A measurement with a multimeter between A0 and GND must confirm the displayed voltage (within the precision of the 10-bit ADC: 5 V / 1024 ≈ 4.9 mV per step).
Common errors
- Applying more than 5 V to an analog input: risk of permanent damage (5 V logic).
- Confusing scales:
analogReadreturns 0–1023, not 0–5 nor 0–255; to drive a PWM output (analogWrite, 0–255), remember to divide by 4. - Unconnected input: the value "dances" because the input is floating.
- Forgetting that the 16 inputs A0–A15 share the single ADC: reading is sequential, which matters for fast measurements.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinodouble-servo.inoArduinopont-uart.inoArduinopwm-respiration.inoArduinopotentiometre-plotter.inoArduino