Lesson 8: Brightness with PWM
Cette page nécessite un navigateur récent (avec support SharedArrayBuffer). Veuillez mettre à jour Chrome, Edge, Firefox ou Safari vers la dernière version.
English
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);
}
}
English
From a knob to brightness
analogReadgives 0–1023, butanalogWritewants 0–255.map(value, 0, 1023, 0, 255)changes one range into the other.
Difficulté 1/5 · 100 pièces + un petit bonus lors de la première réussite aujourd'hui
Make the LED on pin 9 about a quarter as bright as full: analogWrite with 64.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Make a dimmer: read the knob on A0 and set the brightness of the LED on pin 9 with map et analogWrite.
Cliquez sur Exécuter pour voir le résultat ici.