Now, if we look at our
loop
function, it has only two lines in it.
We have moved the
bulk of the work off to the
flash
function. Notice how when we call
flash
we now supply
it with two arguments in parentheses.
Where we define the function at the bottom of the sketch, we have to declare the type of
variable in the parameters. In this case, they are both
int
s.
We are in fact defining new
variables. However, these variables (
numFlashes
and
d
) can only be used within the
flash
function.
This is a good function because it wraps up everything you need in order to flash an
LED. The only information that it needs from outside of the function is to which pin the
LED is attached.
If you wanted, you could make this a parameter too—something that
would be well worth doing if you had more than one LED attached to your Arduino.
Global, Local, and Static Variables
As was mentioned before, parameters to a function can be used only inside that function.
So, if you wrote the following code, you would get an error:
On the other hand, suppose you wrote this:
This code would not result in a compilation error. However, you need to be careful,
because you now actually
have two variables called
x
and they can each have different
values. The one that you declared on the first line is called a
global variable.
It is called
global
because it can be used anywhere
you like in the program, including inside any
functions.
However, because you use the same variable name
Dostları ilə paylaş: