pwm-fade.ino

Arduino UNO R3 · File : pwm-fade.ino · Language : Arduino · Use case : Faire varier progressivement la luminosité d'une LED (respiration)

The LED on a PWM pin (9) breathes up and down in brightness. analogWrite() generates an 8-bit PWM signal (0-255) whose duty cycle drives the LED average brightness.

Hardware

An Arduino Uno R3 (ATmega328P, 5 V, 16 MHz) powered over USB or a 7-12 V barrel jack. 1 LED + 330 Ω resistor.

Wiring

LED anode to pin 9 through the 330 Ω resistor, cathode to GND. Pin 9 is a PWM output on classic AVR boards.

How it works

analogWrite() sets a hardware timer that chops the signal at about 500 Hz. The 0-255 value sets the duty cycle; the loop ramps it in a triangle between 0 and 255.

Running it

In the Arduino IDE, select the « Arduino Uno » board and the matching serial port, then click Upload. Open the serial monitor at 9600 baud to follow the messages.

Variants

Add a potentiometer on A0 to drive brightness with analogRead(), or apply gamma (value^2 / 255) for a more natural ramp.

pwm-fade.ino

// Effet "respiration" : variation progressive de la LED par PWM.
const int LED = 9; // broche PWM (marquee ~ sur les cartes AVR)

int valeur = 0;
int pas = 4;
const int PAUSE = 15; // ms entre deux paliers

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

void loop() {
  analogWrite(LED, valeur);      // PWM 8 bits : 0..255
  Serial.println(valeur);

  valeur += pas;
  if (valeur >= 255) { valeur = 255; pas = -pas; } // sommet : on redescend
  if (valeur <= 0)   { valeur = 0;   pas = -pas; } // bas : on remonte

  delay(PAUSE);
}

// Sur les AVR, analogWrite() pilote les timers 0, 1 et 2 :
// broches 5, 6, 9, 10, 11, 3 selon la carte. La perception de la
// luminosite est logarithmique : pour un rendu plus naturel,
// remplacer valeur par (valeur * valeur) / 255 (gamma 2).

← Back to the board