Fade an LED In
Part of the Outputs section of Coddy's Arduino journey. Lesson 3 of 24.
A variable can hold the brightness. Each time loop() runs, write it to the LED, add a little to it and wait a moment. The LED gets brighter step by step:
int brightness = 0;
void loop() {
analogWrite(9, brightness);
brightness = brightness + 5;
if (brightness > 255) {
brightness = 0;
}
delay(30);
}The brightness lives at the top of the sketch, like the press counter, so it keeps its value from one run of loop() to the next. Made inside loop(), it would be back at 0 every time.
255 is the largest value analogWrite() takes, so the if starts the fade again from 0 once the brightness goes past it.
The step and the wait set the speed: about 50 steps of 30 ms take a second and a half.
Challenge
EasyMake the LED on pin 9 fade in, again and again:
- keep the brightness in a variable made above
setup(), starting at 0 - in
loop(), write it withanalogWrite(), add 5 and wait 30 ms - when it goes past 255, set it back to 0
Press Run and watch the LED, then Check.
Try it yourself
const int ledPin = 9;
// make the brightness variable here, starting at 0
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
// write the brightness, add 5, start again after 255, wait 30 ms
}
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