Fading
This example demonstrates the use of analog output (Pulse Width Modulation
(PWM)) to fade an LED. PWM is a technique for getting an analog-like behavior
from a digital output by switching it off and on very fast and with different ratio
between on and off time.
Hardware Required
Arduino or Genuino board
LED
220 ohm resistor
hook-up wires
breadboard
Circuit
An LED connected to digital output pin 9 through a 220 ohm resistor.
Schematic
Code
In this example two loops are executed one after the other to increase and then
decrease the value of the output on pin 9.
int ledPin = 9; // LED connected to digital pin 9
void setup() {
// nothing happens in setup
}
void loop() {
// fade in from min to max in increments of 5 points:
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade out from max to min in increments of 5 points:
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}