Hardware Reference
In-Depth Information
}
for (int i=255; i>=0; i--)
{
analogWrite(LED, i);
delay(10);
}
}
What does the LED do when you run this code? You should observe the LED
fading from off to on, then from on to off. Of course, because this is all in the
main loop, this pattern repeats ad infinitum. Be sure to note a few differences
in this for loop. In the first loop, i++ is just shorthand code to represent i=i+1 .
S i m i i=i-1. a rl y, i-- is functionally equivalent to i=i-1 . The first for loop fades the
LED up, and the second loop fades it down.
PWM control can be used in lots of circumstances to emulate pure analog con-
trol, but it cannot always be used when you actually need an analog signal. For
instance, PWM is great for driving direct current (DC) motors at variable speeds
(you experiment with this in later chapters), but it does not work well for driving
speakers unless you supplement it with some external circuitry. Take a moment
to examine how PWM actually works. Consider the graphs shown in Figure 2-4.
Figure 2-4: PWM signals with varying duty cycles
PWM works by modulating the duty cycle of a square wave (a signal that
switches on and off). Duty cycle refers to the percentage of time that a square
wave is high versus low. You are probably most familiar with square waves that
have a duty cycle of 50%—they are high half of the time, and low half of the time.
Search WWH ::




Custom Search