🛠 Lire un capteur analogique : potentiomètre et ADC 10 bits

Arduino Leonardo — Board Fiche · debutant · Schéma : IMG-leonardo-debutant-3-leonardo-capteur-analogique.svg — Potentiomètre alimenté en 5V/GND, curseur relié à A0 sur une Leonardo, courbe de valeur à l'écran

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials