Fade In and Out
Part of the Outputs section of Coddy's Arduino journey. Lesson 4 of 24.
To fade back down, the step has to change direction. Keep the step in its own variable, fadeAmount. Adding a negative number makes the brightness go down:
int brightness = 0;
int fadeAmount = 5;
void loop() {
analogWrite(9, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30);
}A minus sign in front of a variable flips its sign: -fadeAmount turns 5 into -5, and -5 back into 5.
The if checks both ends. At the top the step becomes -5 and the LED dims; at the bottom it becomes 5 again and the LED brightens. The LED breathes, and never jumps from bright to dark.
Challenge
EasyMake the LED on pin 9 fade in and then out, again and again:
- a
fadeAmountvariable of 5 besidebrightness - add
fadeAmountto the brightness each timeloop()runs, then wait 30 ms - flip its sign when the brightness reaches 0 or 255
Press Run, then Check.
Try it yourself
const int ledPin = 9;
int brightness = 0;
// make fadeAmount here
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
analogWrite(ledPin, brightness);
brightness = brightness + 5;
if (brightness > 255) {
brightness = 0;
}
delay(30);
}
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