Pretty light effects, standby modes, custom color hues... All possible when you can control the intensity of an LED! Bonus: you can adapt this tutorial to make annoying noises with a speaker. :)
This is our first introduction to PWM! Read on to find out about this powerful technique.
We're going to use the same LED/resistor setup as the Blink sketch – with one important difference: the LED should be attached to pin 9, or any other pin with a little tilde (~) mark next to it.
Load up the Fade example: File > Examples > Basics > Fade
First off, of course, you'll notice the
variables. (This capitalization style is called camel case, one type of capitalization commonly used in code.)
Now, guess what? We're using an ANALOG function to write to a DIGITAL pin! The 0-255 brightness value (that's 2^8) is translated into switching the pin on and off, too fast for the eye to see. At a value of 127 (50% brightness), the LED will be on 50% of the time, off 50% of the time. And the actual length of those pulses gives PWM – pulse width modulation – its name.
So, we're changing
over time. First, we write its starting value of 0 to the
pin. (Yes, you can use variables for both the pin number and the brightness value!)
Next, add 5 brightness points (
), wait 30 milliseconds, and restart the loop. At this rate, the LED will reach full brightness in about a second and a half.
However, if we've hit max brightness, we also flip the sign of
so that it's negative – fading back down to zero, -5 at a time, until it's completely off again. The
in the code signifies "or".
Now try this:
- Modify the "fadeAmount" value to make the effect faster or slower.
- Grab red, green, and blue LEDs (or one RGB LED) and fade them at different rates. Put a sheet of paper over it as a diffuser, or point them at a wall, and see what colors you can make! (Note that different-colored LEDs may need different resistors, to keep Red from hogging all the brightness. More on this later!)
You can use PWM to control speakers, too, and produce "musical" tones at different frequencies. What happens if you swap out the LED and resistor for a small speaker...? (It may be very quiet!)