Hardware Reference
In-Depth Information
current pass through the LED, in which case the circuit would require a 53 Ω
resistor. This is not a standard resistor value. The closest standard resistor value
below 53 ohms is 47 ohms. If you do the math, you'll see that a 47-ohm resistor
would allow 34 mA of current through the LED, above its rated tolerance. If
you re-do the calculations aiming for 20 mA, the new result is 80 Ω. The closest
standard value is 82 Ω, which is close to the target. Therefore, for this example,
the schematic will use an 82 Ω resistor.
Software
It's time to code the application. This sketch illustrates a common beginner's
task with the Arduino, fading an LED. Listing 3-1 presents the source code.
Listing 3-1: Fade
int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many steps to fade the LED each loop
// the setup routine runs once when you press reset or power the board:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading when the LED is fully bright
// or fully off :
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
The led variable is the pin the LED is connected to. You're using pin 9 because
it is one of the PWM pins. That is, it is one of the pins you can call analogWrite()
on. In the setup() function, the pin is set to become an output. Then, the loop()
function adds the value stored in fadeAmount to the variable brightness , looks to
see if the value should be inverted, and then waits for 30 milliseconds. Because
this function is looped, it constantly updates the output pin value, ranging from
 
Search WWH ::




Custom Search