Hardware Reference
In-Depth Information
8. At the end of the loop, i is incremented by 100 , so it is now 300 .
9. This process repeats until i surpasses 1000 and the outer loop function
repeats, setting the i value back to 100 and starting the process again.
Now that you've generated digital outputs from your Arduino, you'll learn
about using PWM to create analog outputs from the I/O pins on your Arduino.
Pulse-WidthModulationwithanalogWrite()
So, you have mastered digital control of your pins. This is great for blinking
LEDs, controlling relays, and spinning motors at a constant speed. But what if
you want to output a voltage other than 0V or 5V? Well, you can't—unless you
are using the digital-to-analog converter (DAC) pins on the Due or are using
an external DAC chip.
However, you can get pretty close to generating analog output values by using
a trick called pulse-width modulation (PWM). Select pins on each Arduino can
use the analogWrite() command to generate PWM signals that can emulate a
pure analog signal when used with certain peripherals. These pins are marked
with a ~ on the board. On the Arduino Uno, Pins 3, 5, 6, 9, 10, and 11 are PWM
pins. If you're using an Uno, you can continue to use the circuit from Figure 2-1
to test out the analogWrite() command with your LED. Presumably, if you
can decrease the voltage being dropped across the resistor, the LED should
glow more dimly because less current will flow. That is what you will try to
accomplish using PWM via the analogWrite() command. The analogWrite()
command accepts two arguments: the pin to control and the value to write to it.
The PWM output is an 8-bit value. In other words, you can write values from
0 to 2 8 -1, or 0 to 255. Try using a similar for loop structure to the one you used
previously to cycle through varying brightness values (see Listing 2-3).
Listing 2-3: LED Fade Sketch—fade.ino
const int LED=9; //define LED for Pin 9
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
}
void loop()
{
for (int i=0; i<256; i++)
{
analogWrite(LED, i);
delay(10);
 
Search WWH ::




Custom Search