Sometimes you need to be able to program your Propeller to repeat certain operations. This ability is useful for simple things, such as blinking light, and more complex tasks, such as robotic sensor navigation.
Blocks of repeating code are called loops. A loop can be set up to repeat a set of blocks forever, or while a defined condition is true, or for a specified number of times.
Open a new project and build the blocks as shown. You can find the conditional repeat block under the CONTROL menu.
The program above first prints the text “This loop repeats forever,” and then moves the cursor to the next line. Then, the program sets up a loop. Inside the loop, there is a block that prints the text “...and ever…” with a new line and a 1-second pause. The program will continue running forever. The only way to stop the program is to reset the Propeller microcontroller.
Many programs need to use loops that run forever, but sometimes it is helpful to break out of a loop. That is where the break block comes in handy.
In the next example, we will set up a new variable and give it a value of 0. Inside of the loop, we will add 1 to the variable using the de/increment block from the VALUES > NUMBERS menu. We will set it to increment, which is just a fancy way of saying "add 1 to the variable." Then, we will use an if...do block to see if our variable is greater than 5, and if it is, break out of the loop.
Modify your program to look like this:
The conditional repeat block has some additional options:
Sometimes, it is helpful for your loop to skip-count. Imagine that you need to turn a motor all the way around, but you want to stop every ten degrees - the repeat item block lets you do just that:
Now, try building a program that skip-counts:
You can use the repeat item block to count down as well. When you change the “by” value in the block, and start with a higher number than you end with, the repeat item block will count down (decrement) instead of up.