🛠 Lire un capteur analogique sur le convertisseur 10 bits
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
- 1 Arduino Micro
- 1 10 kΩ potentiometer (ends connected to 5V and GND, wiper connected to A0)
- 1 LED + 220 to 470 Ω resistor on pin 9
- Micro-USB cable
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
- Applying a value from 0-1023 to analogWrite: values above 255 are truncated, causing the LED to stay fully on. Remember to divide by 4 (>> 2).
- Connecting the LED to a non-PWM pin (for example, pin 4): no variation occurs, and the LED only blinks.
- Confusing A0 with digital pin 0: pin 0 is the RX pin of Serial1 (UART TTL).
- Needing more channels: A6 to A11 are shared with digital pins 4, 6, 8, 9, 10, 12 (12 channels in total, compared to 6 on the Uno).
Other tutorials for this board
- Faire clignoter la LED embarquée (et comprendre les LED TX/RX)
- Lire un bouton avec une résistance de pull-up interne
- Transformer le Micro en clavier USB (HID) avec bouton de sécurité
- Pont Serial vers Serial1 : passerelle USB vers TTL
- Piloter un servo moteur avec le PWM et un potentiomètre
- Sortir des sentiers : registres AVR et interruption externe
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinoclavier-auto-tape.inoArduinosouris-cercle.inoArduinotelecommande-media.inoArduinobouton-clic-souris.inoArduino