Lesson 8: Brightness with PWM
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Half on
analogWrite(9, 128);makes pin 9 switch on and off very fast: on about half of the time.- This is called PWM. An LED looks half as bright.
- The number goes from 0 (always off) to 255 (always on).
- Only pins with a ~ on the board can do this: 3, 5, 6, 9, 10 and 11.
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
for (int b = 0; b <= 255; b = b + 5) { // slowly brighter
analogWrite(9, b);
delay(20);
}
for (int b = 255; b >= 0; b = b - 5) { // slowly darker
analogWrite(9, b);
delay(20);
}
}
From a knob to brightness
analogReadgives 0–1023, butanalogWritewants 0–255.map(value, 0, 1023, 0, 255)changes one range into the other.
Difficulty 1/5 · 100 coins + a small bonus on first completion today
Make the LED on pin 9 about a quarter as bright as full: analogWrite with 64.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Make a dimmer: read the knob on A0 and set the brightness of the LED on pin 9 with map and analogWrite.
Click Run to see the output here.