Hardware Reference
In-Depth Information
common practice to define all your pins as inputs or outputs in the setup. You
start by writing a simple program that sets pin 9 as an output and turns it on
when the program starts.
To write this program, use the pinMode() command to set the direction of
pin 9, and use digitalWrite() to make the output high (5V). See Listing 2-1.
Listing 2-1: Turning on an LED—led.ino
const int LED=9; //define LED for pin 9
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
digitalWrite(LED, HIGH); //Set the LED pin high
}
void loop()
{
//we are not doing anything in the loop!
}
Load this program onto your Arduino, wired as shown in Figure 2-2. In
this program, also notice that I used the const operator before defining the
pin integer variable. Ordinarily, you'll use variables to hold values that may
change during program execution. By putting const before your variable dec-
laration, you are telling the compiler that the variable is “read only” and will
not change during program execution. All instances of LED in your program
will be “replaced” with 9 when they are called. When you are defining values
that will not change, using the const qualifier is recommended. In some of the
examples later in this chapter, you will define non-constant variables that may
change during program execution.
You must specify the type for any variable that you declare. In the preceding
case, it is an integer (pins will always be integers), so you should set it as such.
You can now easily modify this sketch to match the one you made in Chapter 1
by moving the digitalWrite() command to the loop and adding some delays.
Experiment with the delay values and create different blink rates.
UsingForLoops
It's frequently necessary to use loops with changing variable values to adjust
parameters of a program. In the case of the program you just wrote, you can
implement a for loop to see how different blink rates impact your system's
operation. You can visualize different blink rates by using a for loop to cycle
through various rates. The code in Listing 2-2 accomplishes that.
Search WWH ::




Custom Search