🛠 LED qui respire en PWM
Objectives
Make an LED "breathe" using Pulse Width Modulation (PWM): analogWrite from 0 to 255, triangular ramp, then brightness control via the light sensor. Identify the PWM pads (5, 6, 9, 10, 11 on Simple/SimpleSnap) and the 40 mA current limit per pad.
Materials
- 1 LilyPad SimpleSnap + 3.7 V battery
- 1 LilyPad LED on a PWM pad (9 recommended, PWM available on all models)
- 1 LilyPad light sensor on A2 (light-controlled variant)
- FTDI adapter for serial testing
Complete code
// LED « qui respire » sur pastille PWM 9 — analogWrite 0..255
const uint8_t LED = 9; // PWM sur toutes les LilyPad (5/6/9/10/11 sur Simple)
const uint8_t CAPTEUR = A2; // option : luminosité ambiante
bool modeCapteur = false; // true = luminosité imposée par le capteur
uint16_t niveau = 0;
int8_t pas = 4; // avance de 4/255 toutes les 10 ms
void setup {
pinMode(LED, OUTPUT);
}
void loop {
if (modeCapteur) {
int brut = analogRead(CAPTEUR); // 0..1023
analogWrite(LED, map(brut, 0, 1023, 0, 255));
} else {
if (niveau >= 255) pas = -4; // sommet : on redescend
if (niveau <= 0) pas = 4; // fond : on remonte
niveau += pas;
analogWrite(LED, niveau);
}
delay(10);
}
Expected verification
The LED brightness increases for about 0.65 s, decreases, increases again, in a smooth loop: the eye perceives a breathing effect. In sensor mode, the LED turns off in darkness and turns on fully under a flashlight. The LED does not blink roughly: if it stays only on/off, the chosen pad is not a PWM output.
Common errors
- analogWrite on a non-PWM pad: the LED blinks too fast for the eye or stays stuck at mid-voltage.
- Confusing 0–255 (PWM) and 0–1023 (ADC): map is essential between the sensor and the LED.
- Overloading the pad: 40 mA maximum per pin (documented); for multiple LEDs, distribute them across several pads or add a transistor.
- Ramp with a uint8_t counter: level += step silently overflows at 255; use uint16_t as done here.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinopwm-respiration.inoArduinoluxmetre-couture.inoArduinointerrupteur-tilt.inoArduinoservo-balayage.inoArduino