Hardware Reference
In-Depth Information
If you've got everything right, you should see a fading LED! Just like those
fancy computers! Let's take a look at the code in
Example 3-2
.
Example 3-2. The Arduino fade example
int
led
=
9
;
//
int
brightness
=
0
;
//
int
fadeAmount
=
5
;
//
void
setup
()
{
//
pinMode
(
led
,
OUTPUT
);
//
}
void
loop
()
{
//
analogWrite
(
led
,
brightness
);
//
brightness
=
brightness
+
fadeAmount
;
//
if
(
brightness
==
0
||
brightness
==
255
)
{
//
fadeAmount
=
-
fadeAmount
;
//
}
delay
(
30
);
//
}
Store the integer 9 into a new variable called
led
. This is the pin
number connected to the LED.
Store the integer 0 into a new variable called
brightness
. This is where
the sketch will keep track of the brightness level.
Store the integer 5 into a new variable called
fadeAmount
. This will
define the amount of steps in brightness to take each time the
brightness is changed.
Start the
setup
function, which is only executed once at the start of
the sketch.
Set
led
(pin 9) as an output.
Start the
loop
function, which is executed over and over again after
the
setup
function is finished.
Set
led
(pin 9) to the PWM value as determined by the variable
brightness
. The first time executing this loop, it will be 0 (completely
off) because the value of
brightness
was initialized as 0 at the
beginning of the sketch.
Take the current value of
brightness
, add
fadeAmount
to it and then
assign that amount to
brightness
. In other words, add
fadeAmount
to
brightness
.
If
brightness
equals 0 or 255, execute the code within the curly
brackets.