Until
now our programming has been limited to running through the code once,
and then the program stops functioning. This is clearly not suitable
for a robot, which must be able to follow it's commands continuously
for the length of time it is switched on. To do this we use loops.
We also
want our robots to make decisions based on data from its sensors, for
this we need conditional statements. Loops themselves contain
conditional statements in order to tell them when to run and how long
to continue.
There
are several different loop commands, letting us control the function
of the robot in a variety of ways.
Do
Loops:
The
simple Do loop can be used to enclose your whole program, when it
reaches the end of the code it returns to the beginning and starts
again. We can apply this to our program used in the introduction.
As you
will see when you run this program, the statement is no longer
displayed once, but continues to print as long as the program runs
(you should press the reset button to stop it)
Now for
something slightly more useful. We can add a conditional statement to
the do loop by using a ' while ' statement. This lets us tell the
Robocore when to stop looping.
For
Loop:
We can
set up the same loop using the for statement remove the Do while, Loop
and i=i+1 lines and replace them with:
Do While
For I = 1 to 10 Step 1
Loop
Next
The loop
runs from 1 to 10 stepping up 1 each loop, this removes the need for
the line I=I+1.
Run the
program to check that you have got it right.
Now for
something a little more complex, instead of just doing one sum, we can
automate the Robocore to do 10 different sums for us by changing the
equation to
AnswerI = I*5
Now the
Robocore takes the number of loops completed and multiplies it by
five. When you run this program you should now get the answers 5,10,15
up to 50.
If
Statement:
We can
run a conditional statement without using a loop with an if statement.
These are used as follows
The best
way to learn is to experiment, make your own program with what you've
learnt and you'll soon feel more confident
|