Programming Arduino Getting Started with Sketches



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

4
Functions
This chapter
focuses mostly on the type of functions that you can write yourself rather
than the built-in functions such as 
digitalWrite
and 
delay
that are already defined for you.
The reason that you need to be able to write your own functions is that as sketches start
to get a little complicated, then your 
setup
and 
loop
functions will grow and grow until
they are long and complicated and it becomes difficult to see how they work.
The biggest problem in software development of any sort is managing complexity. The
best programmers write software that is easy to look at and understand and requires very
little in the way of explanation.
Functions are a key tool in creating easy-to-understand sketches that can be changed
without difficulty or risk of the whole thing falling into a crumpled mess.
What Is a Function?
A function is a little like a program within a program. You can use it to wrap up some little
thing that you want to do. A function that you define can be called from anywhere in your
sketch and contains its own variables and its own list of commands. When the commands
have been run, execution returns to the point just after wherever it was in the code that
called the function.
By way of an example, code that flashes a light-emitting diode (LED) is a prime
example of some code that should be put in a function. So let’s modify our basic “blink 20
times” sketch to use a function that we will create called 
flash
:


So, all we have really done here is to move the four lines of code that flash the LED
from the middle of the 
for
loop to be in a function of their own called 
flash
. Now you can
make the LED flash any time you like by just calling the new function by writing 
flash()
.
Note the empty parentheses after the function name. This indicates that the function does
not take any parameters. The delay value that it uses is set by the same 

Yüklə 5,42 Kb.

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