🛠 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 the 6 PWM pins of the Pro Mini (3, 5, 6, 9, 10, 11 — 8-bit resolution via the ATmega328P timer). The potentiometer connected to A0 (0-1023) is scaled to 0-255 to control the duty cycle. Remember the absolute limit: 40 mA maximum per pin, regardless of whether it is the 5 V or 3.3 V model.
Hardware
- 1 × Arduino Pro Mini (ATmega328P; confirmed PWM pins: 3, 5, 6, 9, 10, 11)
- 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
- FTDI/CP2102 adapter for serial feedback
Complete code
// Variateur PWM : potentiometre A0 -> LED broche 9
const uint8_t POT = A0;
const uint8_t LED_PWM = 9; // broche PWM (3, 5, 6, 9, 10 ou 11)
uint32_t derniere = 0;
void setup {
pinMode(LED_PWM, OUTPUT);
Serial.begin(57600);
}
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
Turning the potentiometer, the LED gradually turns off (0) then increases in brightness up to full intensity (255) without steps. By looking at the LED through a phone camera in slow motion, you can distinguish the PWM flickering while the eye perceives continuous light. On the 3.3 V model, the PWM "high" voltage is 3.3 V: choose the resistor accordingly (the LED will be slightly less bright than at 5 V).
Common errors
- Using
analogWriteon a non-PWM pin (e.g., pin 4): 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 40 mA max 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; the Pro Mini has no digital-to-analog converter.
- Using pins 11-13 for PWM while using SPI: these are also MOSI/MISO/SCK — the two uses conflict with each other.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-poussoir.inoArduinopwm-fade.inoArduinocapteur-lumiere-ldr.inoArduinoservo-balayage.inoArduinoruban-neopixel.inoArduino