Programming Arduino Getting Started with Sketches


delayPeriod function that you used before. Parameters



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

delayPeriod
function that you used before.
Parameters
When dividing your sketch up into functions, it is often worth thinking about what service
a function could provide. In the case of 
flash
, this is fairly obvious. But this time, let’s
give this function parameters that tell it both, how many times to flash and how short or
long the flashes should be. Read through the following code and then I will explain just
how parameters work in a little more detail.


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 

Yüklə 5,42 Kb.

Dostları ilə paylaş:
1   ...   25   26   27   28   29   30   31   32   ...   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