Programming Arduino (1) Pages 67
Programming Arduino (1) Pages 67
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 , which
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 :
// sketch 4-01