🛠 Lire un capteur analogique (potentiomètre)

Arduino Mega ADK (Rev3) · debutant · Schéma : IMG-mega-adk-debutant-3-mega-adk-capteur-analogique.svg — Mega ADK, potentiomètre 10 kΩ sur A0 (5 V / GND / curseur) et LED sur la broche PWM 9

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

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

  1. Potentiometer whose two outer pins are not connected to 5 V and GND: floating reading or stuck at 0/1023.
  2. LED connected to a non-PWM pin: analogWrite has no effect — check the list 2-13 and 44-46.
  3. 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.
  4. Analog input left floating: the value "breathes" on its own, normal behavior of a high-impedance input.
  5. 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

← Back to the board 🛠 All tutorials