🛠 Variateur d'intensité LED avec PWM

Arduino Nano (Classic, ATmega328P) · intermediaire · Schéma : IMG-nano-classic-intermediaire-4-nanoc-pwm-led.svg — LED avec résistance sur broche PWM 9 de l'Arduino Nano, potentiomètre sur A0 pilotant analogWrite

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials