Figure 3-4
A sketch that will compile
The line
void setup()
means that you are defining a function called
setup
. In Arduino,
some functions are already defined for you, such as
digitalWrite
and
delay
, whereas you
must or can define others for yourself.
setup
and
loop
are
two functions that you must
define for yourself in every sketch that you write.
The important thing to understand is that here you are not calling
setup
or
loop
like you
would call
digitalWrite
, but you are actually creating these functions so that the Arduino
system itself can call them. This is a difficult concept to grasp, but one way to think of it is
as being similar to a definition in a legal document.
Most legal documents have a “definitions” section that might say, for example,
something like the following:
By defining a term in this way—for example, simply using the word “author” as
shorthand for “The person or persons responsible for creating the book”—lawyers can
make their documents shorter and more readable. Functions
work much like such
definitions. You define a function that you or the system itself can then use elsewhere in
your sketches.
Going back to
void
, these two functions (
setup
and
loop
) do not return a value as some
functions do, so you have to say that they are void, using the
void
keyword. If you
imagine a function called
sin
that performed the trigonometric function of that name, then
this function would return a value. The value returned to use from the call would be the
sin of the angle passed as its argument.
Rather like a legal definition uses words to define a term, we write functions in C that
can then be called from C.
After the special keyword
void
comes the name of the function and then parentheses to
contain any arguments.
In this case, there are no arguments,
but we still have to include
the parentheses there. There is no semicolon after the closing parenthesis because we are
defining a function rather than calling it, so we need
to say what will happen when
something does call the function.
Those things that are to happen when the function is called must be placed between
curly braces. Curly braces and the code in between them are known as a
block
of code,
and this is a concept that you will meet again later.
Note that although you do have to define both the functions
Dostları ilə paylaş: