🛠 Lire un capteur analogique avec l’ADC 10 bits

Arduino Mega 2560 (Rev3) · debutant · Schéma : IMG-mega-2560-debutant-3-capteur-analogique.svg — potentiomètre 10 kΩ monté en pont diviseur entre 5 V et la masse, curseur vers l’entrée analogique A0 de l’Arduino Mega 2560

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials