In this case, you are going to set the values for the durations at the time that you create
the array. The syntax for doing this is to use curly braces and then values each separated
by commas. Don’t forget the semicolon on the end of the line.
You can access any given element of the array using the square bracket notation. So, if
you want to get the first element of the array, you can write the following:
To
illustrate this, let’s create an array and then print out all its values to the Serial
Monitor:
Upload the sketch to your board and then open the Serial Monitor. If all is well, you will
see something like
Figure 5-1
.
This is quite neat, because if you wanted to add
more durations to the array, all you
would need to do is add them to the list inside the curly braces and change “9” in the
for
loop to the new size of the array.
Figure 5-1
The Serial Monitor Showing the Output of Sketch 5-01
You have to be
a little careful with arrays, because the compiler will not try and stop
you from accessing elements of data that are beyond the end of the array. This is because
the array is really a pointer to an address in memory, as shown in
Figure 5-2
.
Programs
keep their data, both ordinary variables and arrays, in
memory
.
Computer
memory is arranged much more rigidly than the human kind of memory. It is easiest to
think of the memory in an Arduino as a collection of pigeonholes.
When you define an
array of nine elements, for example, the next available nine pigeonholes are reserved for
its use and the variable is said to point at the first pigeonhole or
element
of the array.
Going back to our point about access being allowed beyond the bounds of your array, if
you decided to access
Dostları ilə paylaş: