🛠 Lire un capteur analogique (potentiomètre)
Objectives
Read an analog sensor — here a potentiometer — on one of the 16 analog inputs of the ATmega2560 (10-bit conversion, values 0 to 1023, default 5 V reference, adjustable via the AREF pin and analogReference), then control the brightness of an LED using PWM. Reminder of the board's resources: 15 PWM channels (pins 2 to 13 and 44 to 46) controlled by analogWrite on 0–255, and 54 digital pins in total.
Hardware
- 1 × Arduino Mega ADK
- 1 × 10 kΩ potentiometer: left pin → 5 V, right pin → GND, wiper (middle pin) → A0
- 1 × LED + 220 Ω resistor on pin 9 (valid PWM pin)
- USB type B cable
- Do not connect anything to pin 7 (MAX3421E RST)
Complete code
// mega-adk-capteur-analogique.ino — Board: "Arduino Mega ADK"
const byte ENTREE_ANA = A0; // 16 entrées analogiques, 10 bits : 0..1023
const byte LED_PWM = 9; // PWM : broches 2-13 et 44-46
void setup {
Serial.begin(9600);
pinMode(LED_PWM, OUTPUT);
analogReference(DEFAULT); // référence 5 V par défaut
}
void loop {
int brut = analogRead(ENTREE_ANA); // 0..1023
int valeurMoyenne = 0;
for (int i = 0; i < 8; i++) { // moyenne simple sur 8 échantillons
valeurMoyenne += analogRead(ENTREE_ANA);
delay(1);
}
valeurMoyenne /= 8;
byte consigne = map(valeurMoyenne, 0, 1023, 0, 255);
analogWrite(LED_PWM, consigne); // 0..255
Serial.print(F("brut=")); Serial.print(brut);
Serial.print(F(" moyenne="")); Serial.print(valeurMoyenne);
Serial.print(F(" pwm="")); Serial.println(consigne);
delay(100);
}
Expected verification
Turning the potentiometer, the read value follows 0 → 1023 and the LED gradually turns off then brightens. The average of 8 samples stabilizes the serial display. The steps of the 8-bit PWM remain barely visible to the eye on the ATmega2560.
Common errors
- Potentiometer whose two outer pins are not connected to 5 V and GND: floating reading or stuck at 0/1023.
- LED connected to a non-PWM pin: analogWrite has no effect — check the list 2-13 and 44-46.
- Confusion between the 0-1023 (analogRead) and 0-255 (analogWrite) scales: without map, the LED saturates as soon as the first quarter of the range is reached.
- Analog input left floating: the value "breathes" on its own, normal behavior of a high-impedance input.
- Real sensor (LDR, TMP36…): check the voltage scale; never exceed 5 V on a pin, power the sensor with 3.3 V if needed — the 3V3 pin is limited to 50 mA.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinoscan-hote-usb.inoArduinoadk-chat-android.inoArduinoadk-telemetrie.inoArduinohote-clavier-usb.inoArduino