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
Dostları ilə paylaş: