🛠 Variateur d'intensité LED avec PWM
Objectives
Use Pulse Width Modulation (PWM) to vary the brightness of an LED: the Arduino core exposes analogWrite(pin, 0-255) on PWM pins (6 pins on the Nano's digital header). The potentiometer on A0 (0-1023) is scaled to 0-255 to control the duty cycle at ~490 Hz.
Hardware
- 1 × Classic Arduino Nano (ATmega328P, 6 PWM pins)
- >
- 1 × LED + 1 × 220 Ω resistor (or an NPN transistor/MOSFET for a power LED, max 40 mA per pin)
- 1 × 10 kΩ potentiometer on A0
Complete Code
// Variateur PWM : potentiometre A0 -> LED broche 9
const uint8_t POT = A0;
const uint8_t LED_PWM = 9; // broche PWM (marque ~ sur le silk)
uint32_t derniere = 0;
void setup {
pinMode(LED_PWM, OUTPUT);
Serial.begin(9600);
}
void loop {
if (millis - derniere >= 20) {
derniere = millis;
int brut = analogRead(POT); // 0..1023
uint8_t rapport = map(brut, 0, 1023, 0, 255);
analogWrite(LED_PWM, rapport); // 0..255
Serial.println(rapport);
}
}
Expected Verification
When turning the potentiometer, the LED gradually turns off (0) and then increases in brightness up to full intensity (255) without steps. By viewing the LED through a phone camera in slow motion, you can distinguish the PWM flickering (~490 Hz on pins 9/10 of the 328P) while the eye perceives continuous light.
Common Errors
- Using
analogWriteon a non-PWM pin: the pin behaves in an all-or-nothing manner (0 = off, any other value = permanently on). - Connecting a power LED directly to the pin: this exceeds the max 40 mA per pin and burns out the output; use a transistor instead.
- Confusing scales:
analogWritetakes 0-255,analogReadreturns 0-1023 — hence the mandatorymap. - Expecting a real analog voltage: PWM is a square wave filtered by visual persistence, not a true DAC output.
Other tutorials for this board
Code examples for this board
buzzer-melodie.inoArduinoservo-sweep.inoArduinoultrason-hcsr04.inoArduinolcd-i2c.inoArduinoeeprom-contre.inoArduinosommeil-watchdog.inoArduino