🛠 Lire un capteur analogique sur le convertisseur 10 bits

Arduino Micro · debutant · Schéma : IMG-micro-debutant-3-micro-capteur-analogique.svg — Potentiomètre monté en diviseur de tension sur A0 d'une Arduino Micro, curseur vers A0, extrémités vers 5V et GND, LED avec résistance sur la broche PWM 9

Objectives

Read an analog sensor (potentiometer) on input A0, understand the 10-bit analog-to-digital converter (0 to 1023) of the ATmega32U4, and control an LED using PWM on one of the 7 PWM pins (3, 5, 6, 9, 10, 11, 13).

Hardware

Complete code

// Potentiometre sur A0 -> LED PWM sur broche 9.
// ADC 32U4 : 10 bits (0..1023) ; analogWrite : 8 bits (0..255), donc >> 2.
const uint8_t KNOB = A0;
const uint8_t LED  = 9;   // broche PWM : 3,5,6,9,10,11 ou 13

void setup {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop {
  int brut = analogRead(KNOB);   // 0..1023
  analogWrite(LED, brut >> 2);   // 0..255
  Serial.println(brut);
  delay(10);
}

Expected verification

Turning the potentiometer causes the displayed value to go from 0 to 1023, and the LED lights up progressively. At mid-position, the value read is approximately 512.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials