Make Electronics

(nextflipdebug2) #1

Experiment 34: Hardware Meets Software


304 Chapter 5


Loops
Here’s another thing I’d like you to try. Rewrite your program code as shown
here and download it onto the PICAXE:
main:
for b0 = 1 to 5
high 1
pause 200
low 1
pause 200
next
wait 2
goto main
Note that b0 is letter b followed by a zero, not letter b followed by letter O. The
extra indents once again are added to make the listing easier to understand.
The four lines beginning “high 1” and ending “pause 200” will be executed re-
peatedly. It’s helpful to see them as a block.
Watch the light and see what happens. It should flash five times quickly, then
wait for two seconds, and then repeat. You just added a loop to your program.
You can use a loop if you want something to happen more than once.
b0 is known as a variable. Think of it as being like a little “memory box” with its
name, b0, on a label on the outside. Figure 5-141 illustrates this concept. This
particular memory box can contain any number from 0 through 255. The loop
begins by telling the computer to put number 1 in the box, then process the
remaining statements, until the word “next” sends the processor back to the
first line, at which point it adds 1 to the contents of b0. If the value of b0 is 5 or
less, the loop repeats. If the value is 6, the loop has run five times, so it’s over,
and the PICAXE skips down to the “wait 2” statement after “next.” See Figure
5-142 for an annotated version of the program listing.
“Wait” is a PICAXE command that is measured in whole seconds, so “wait 2”
waits for 2 seconds. Then “goto main” begins the procedure all over again.
If your flashing-light demo worked out as planned, it’s time to take the next
step and make the chip do something more useful.

Go back to the beginning
and start all over again.

Label identifying
this piece of the program.

Use b0 to count
from 1 to 5.
Has b0 reached 6 yet?
If so, skip down beyond
the "next" statement.

Go back to line 2
and add 1 to b0.

Obey these
instructions
five times.

Figure 5-142. The blue annotations explain what the program, on the right, is telling the
PICAXE to do.

Figure 5-141. To understand how a program
works, visualize a variable as being like a
“memory box” with its name on the out-
side and a number stored on the inside.

Free download pdf