Join Rae Hoyt for an in-depth discussion in this video Fading an LED with PWM with code, part of Learning Arduino: Pulse Width Modulation.
- [Voiceover] In this next example, I'm going to use the Arduino to slowly fade an LED in and out. In the Arduino I-D-E, I will select file, examples, basics, fade. With the use of the analog-right function, I can adjust the brightness of an LED. By keeping track of the brightness and slowly adjusting that value, I can make an LED fade in and out. In this program, three variables are declared. LED, brightness, and fade amount. In the set-up function, pin mode sets pin 9 as output, which, as I mentioned earlier, is unnecessary, as analog-right can handle that declaration.
In the loop, the brightness value is sent to the LED with the analog-right command. The brightness value is then adjusted by fade amount. In this case, five. The program checks to see if the value of brightness is zero or 255. If so, the Arduino sets fade value to the additive inverse of fade value. The additive inverse of a number is the number, that when added to the number, yields zero.
So if fade amount equals five, the additive inverse is negative five. The opposite is also true. This happens first when the value reaches 255. At this point, fade value is five. Arduino changes the sign of the value making fade value negative five. Now, each time the loop executes, the program adds negative five to brightness. Once the value of brightness falls back to zero the condition rings true again. This time, fade value is negative five.
So the Arduino again swaps the sign of the value, setting the fade value back to five. This happens over and over again while the LED fades in and out. When I upload and verify this code you can see that the LED gets brighter and dimmer over time. Because this is happening in the loop, it will continue to execute until the Arduino is unplugged. Back in the code, I'm going to change fade amount to 10. I also need to change the upper bound of the if statement to 250.
Otherwise, the statement will never execute as true. Now, when I reupload the code, you can see the fading happening faster. I'll change the upper bound back to 255 and now I'll set the fade value to one. When I upload this code, it now takes the LED longer to fade in and out. However, when it fades all the way down it takes quite a while for it to turn back on.
This is because the LED appears off around the value of 100. So I'm going to set the lower bound of the if statement to 100. Now, the Arduino will not count down lower than 100. The LED still fades slowly, but only remains off for a few moments between pulses.
- Using basic PWM output
- Adjusting the brightness of LEDs
- Color mixing with RGB LEDs
- Using analog inputs to drive output
- Testing components with a multimeter
- Using the map function
- Debugging code efficiently with the serial monitor
- Controlling servos and motors