Programming Arduino Getting Started with Sketches


x inside the function, as a parameter, you cannot use the global variable  x



Yüklə 5,42 Kb.
Pdf görüntüsü
səhifə30/78
tarix22.12.2023
ölçüsü5,42 Kb.
#189286
1   ...   26   27   28   29   30   31   32   33   ...   78
Arduino SimonMonk 2011

x
inside the function, as a parameter,
you cannot use the global variable 
x
simply because whenever you refer to 
x
inside the
function, the “local” version of 
x
has priority. The parameter 
x
is said to shadow the global
variable of the same name. This can lead to some confusion when trying to debug a
project.
In addition to defining parameters, you can also define variables that are not parameters
but are just for use within a function. These are called 
local variables.
For example:
The local variable 
timesToFlash
will only exist while the function is running. As soon as
the function has finished its last command, it will disappear. This means that local
variables are not accessible from anywhere in your program other than in the function in
which they are defined.
So, for instance, the following example will cause an error:


Seasoned programmers generally treat global variables with suspicion. The reason is
that they go against the principal of encapsulation. The idea of 
encapsulation
is that you
should wrap up in a package everything that has to do with a particular feature. Hence
functions are great for encapsulation. The problem with “globals” (as global variables are
often called) is that they generally get defined at the beginning of a sketch and may then
be used all over the sketch. Sometimes there is a perfectly legitimate reason for this. Other
times, people use them in a lazy way when it would be far more appropriate to pass
parameters. In our examples so far, 
ledPin
is a good use of a global variable. It’s also very
convenient and easy to find up at the top of the sketch, making it easy to change. Actually,
ledPin
is really a constant, because although you may change it and then recompile your
sketch, you are unlikely to allow the variable to change while the sketch is actually
running. For this reason, you may prefer to use the 
#define
command we described in
Chapter 3
.
Another feature of local variables is that their value is initialized every time the function
is run. This is nowhere more true (and often inconvenient) than in the 
loop
function of an
Arduino sketch. Let’s try and use a local variable in place of global variable in one of the
examples from the previous chapter:
Sketch 4-03 is based on the sketch 3-09, but attempts to use a local variable instead of
the global variable to count the number of flashes.
This sketch is broken. It will not work, because every time 

Yüklə 5,42 Kb.

Dostları ilə paylaş:
1   ...   26   27   28   29   30   31   32   33   ...   78




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin