5 Arrays and Strings After reading Chapter 4
, you have a reasonable appreciation as to how to structure your
sketches to make your life easier. If there is one thing that a good programmer likes, it’s an
easy life. Now our attention is going to turn to the data that you use in your sketches.
The book
Algorithms + Data Structures = Programs by Niklaus Wirth has been around
for a good while now, but still manages to capture the essences of computer science and
programming in particular. I can strongly recommend it to anyone who finds themselves
bitten by the programming bug. It also captures the idea that to write a good program, you
need to think about both the algorithm (what you do) and the structure of the data you use.
You have looked at
loop s,
if statements, and what is called the “algorithmic” side of
programming an Arduino; you are now going to turn to how you structure your data.
Arrays Arrays are a way of containing a list of values. The variables that you have met so far have
contained only a single value, usually an
int . By contrast, an array contains a list of
values, and you can access any one of those values by its position in the list.
C, in common with the majority of programming languages, begins its index positions
at 0 rather than 1. This means that the first element is actually element zero.
To illustrate the use of arrays, we could create an example application that repeatedly
flashes “SOS” in Morse code using the Arduino board’s built-in LED.
Morse code used to be a vital method of communication in the 19th and 20th centuries.
Because of its coding of letters as a series of long and short dots, Morse code can be sent
over telegraph wires, over a radio link, and using signaling lights. The letters “SOS” (an
acronym for “save our souls”) is still recognized as an international signal of distress.
The letter “S” is represented as three short flashes (dots) and the letter “O” by three
long flashes (dashes). You are going to use an array of