The
flashSequence
Function
We have assumed a function called
flashSequence
and made use of it, but now you need
to write it. We have planned for it to take a string containing a series of dashes and dots
and to make the necessary flashes with the correct timings.
Thinking about the algorithm for doing this, you can break it into the following steps:
• For each element of the string of dashes and dots (such as .-.-)
• flash that dot or dash Using the concept of programming by intention, let’s keep the
function as simple as that.
The Morse codes are not the same length for all letters, so you need to loop around the
string until you encounter the end marker,
\
0. You also need a counter variable called i that
starts at 0 and is incremented as the processing looks at each dot and dash:
Again, you delegate the actual job of flashing an individual dot or dash to a new method
called
flashDotOrDash
, which actually turns the LED on and off. Finally, when the
program has flashed the dots and dashes, it needs to pause for three dots worth of delay.
Note the helpful use of a comment.
The
flashDotOrDash
Function
The last function in your chain of functions is the one that actually does the work of
turning the LED on and off. As its argument, the function has a single character that is
either a dot (.) or a dash (–).
All the function needs to do is turn the LED on and delay for the duration of a dot if it’s
a dot and three times the duration of a dot if it’s a dash, then turn the LED off again.
Finally it needs to delay for the period of a dot, to give the gap between flashes.
Putting It All Together
Putting all this together, the full listing is shown in sketch 5-05. Upload it to your Arduino
board and try it out. Remember that to use it, you need to open the Serial Monitor and type
some text into the area at the top and click Send. You should then see that text being
flashed as Morse code.
This sketch includes a loop function that is called automatically and repeatedly calls a
flashSequence function that you wrote, which itself repeatedly calls a flashDotOrDash
function that you wrote, which calls digitalWrite and delay functions that are provided by
Arduino!
This is how your sketches should look. Breaking things up into functions makes it much
easier to get your code working and makes it easier when you return to it after a period of
not using it.
Conclusion
In addition to looking at strings and arrays in this chapter, you have also built this more
complex Morse translator that I hope will also reinforce the importance of building your
code with functions.
In the next chapter, you learn about input and output, by which we mean input and
output of analog and digital signals from the Arduino.
|