We’ve learned how to turn an LED completely ON (HIGH) and completely OFF (LOW). But what if we want it to be 50% bright?
Digital pins can only output exactly 5V or exactly 0V. They cannot output 2.5V. To achieve intermediate brightness, we have to trick the human eye using a technique called Pulse Width Modulation (PWM).
Creating smooth fading effects using PWM.
Imagine you are turning a light switch on and off as fast as you can. If you turn it on and off 100 times a second, the light bulb will look like it is constantly glowing, but at a dimmer level than if it were just left on.
That is exactly what PWM does. The Arduino turns the 5V pin on and off incredibly fast.
This percentage is called the Duty Cycle.
Not all pins on the Arduino Uno can do PWM. Look at the numbers next to the digital pins. Some of them have a small tilde symbol (~) next to them: Pins 3, 5, 6, 9, 10, and 11. These are your PWM pins.
analogWrite()To use PWM, we use the analogWrite() function.
Unlike digitalWrite() which accepts HIGH (1) or LOW (0), analogWrite() accepts a number between 0 and 255.
analogWrite(9, 0); // Completely OFF (0% duty cycle)analogWrite(9, 127); // 50% BrightnessanalogWrite(9, 255); // Completely ON (100% duty cycle)Let’s write a script that smoothly fades an LED up and down on Pin 9.
int ledPin = 9; // LED connected to digital pin 9
int brightness = 0; // How bright the LED is
int fadeAmount = 5; // How many points to fade the LED by
void setup() {
// pinMode isn't strictly required for analogWrite,
// but it's good practice.
pinMode(ledPin, OUTPUT);
}
void loop() {
// Set the brightness of pin 9:
analogWrite(ledPin, brightness);
// Change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// Reverse the direction of the fading at the ends:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// Wait for 30 milliseconds to see the dimming effect
delay(30);
}
Now you have a pulsing, “breathing” LED! This technique is used everywhere, from dimming your smartphone screen to controlling the speed of motors in drones.
[Experimenting with different colors? Grab this Diffused RGB LED Pack to try fading multiple colors!]