Hardware Reference
In-Depth Information
Now for the i nal section of code.
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH voltage level)
delay(200); // wait for a second
digitalWrite(led, LOW); // turn the LED off, LOWvoltage
delay(200); // wait for a second
}
Again, the code starts with a comment, giving you an idea of what this por-
tion of code will do. This is a function declaration for a function called loop() .
It does not require any parameters to run.
Inside of loop, you'll see the function digitalWrite() . As you might have
guessed from the name of the function, it performs a write action on a pin in
digital format. It sets the pin status to a logical 1 (HIGH) or a logical 0 (LOW).
The i rst time the function is called in this sketch, it sets the pin to a logical 1.
The code then calls the delay() function with an argument of 1000. The delay
function tells the microcontroller to wait for a specii ed number of milliseconds
before proceeding to the next instruction. In this case, it tells the microcontroller
to wait for 1 second before proceeding. So, the program turns on a pin and then
waits for 1 second. The rest of the code is similar; a digitalWrite is performed,
this time setting the pin to a logical 0 (LOW), and then waits for another second.
For those of you used to developing applications in C, you might have noticed
that the Arduino code does not have a main() function. In C, the main() func-
tion is used as an entry point; that is to say, it is the function that is called when
the program starts. This is true for systems programming, where an operating
system takes care of initializing everything required by the program, but this
is not the case on embedded systems.
The Arduino requires that two functions be present; setup() and loop() . These
two functions must be present, even if they are empty, but they rarely will be.
The setup() function is called when a sketch starts and is used to initialize
variables, pin modes, and other components for your sketch. It is good practice
to keep initialization code away from the work code, making things clearer. It
also has the advantage of making your program more robust. Although it is
perfectly possible to set up a pin as required just before performing an action,
it is best to have everything completely set up before starting your program.
Looking into the setup() function can tell you immediately if you have cor-
rectly set up a pin, instead of looking through long lines of code in the work
section. In this example, setup() contained a command to change the status
of a pin, setting it to output.
Search WWH ::




Custom Search