Dim an LED With PWM
Part of the Outputs section of Coddy's Arduino journey. Lesson 1 of 24.
digitalWrite() knows two levels: on or off. To make an LED glow dimly, the board switches the pin on and off hundreds of times a second. Your eye cannot follow the flicker and sees the average: a pin that is on a quarter of the time looks a quarter as bright.
This trick is called PWM, pulse width modulation. The share of time the pin is on is its duty cycle.
analogWrite(pin, value) sets it with a number from 0 to 255:
analogWrite(9, 0); // always off
analogWrite(9, 64); // on a quarter of the time
analogWrite(9, 127); // on about half the time
analogWrite(9, 255); // always onOnce you write a value, the board keeps the pin pulsing on its own, even during delay(), until you write a new one. analogWrite() makes the pin an output by itself; pinMode(9, OUTPUT) in setup() still says what the pin is for.
Challenge
EasyThe red LED is on pin 9. Make it glow at a quarter of its full brightness:
- a quarter of 255 is about 64
- write it with
analogWrite()
Press Run to watch it, then Check.
Try it yourself
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
// set the LED to a quarter brightness here
}
void loop() {
// nothing to repeat: the pin keeps pulsing on its own
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
Practice on your own: Arduino playground