LEGO Mindstorms

Loops

How to loop over code

What are loops?

Loops are among the most basic and powerful programming concepts. A loop in a computer program is an instruction that repeats until a condition is reached. 

In a loop structure, the loop asks a question, which is answered as true or false. If the answer is true, the actions in the loop are executed until the question or /“condition/” returns an answer of false. If the question is answered as false initially, the actions in the loop will not run. 

An example of a condition in a loop are the brick buttons. When a button is pressed on the EV3 Brick, the loop will stop running the commands inside it. This is done with the following code. 

How does that work?

As you can see, the loop has the move command inside it, which is continuously executed, until the selected button on the brick is pressed. You can actually choose which button to press on the brick (Red) and whether to stop when the button is pressed, released, or bumped (Blue)!  

NOTE: We recommend setting your motor run type to coast rather than brake when using loops. (Green).

Time Based Loops

You can also use a time-based loop. The loop will execute only for the amount of time chosen.

In the loop above, the move block will execute for the number of seconds chosen (Blue). 

Count Based Loops

Similarly, we can also do a count-based loop. This loop will run for the number of times chosen. So, all the commands in the loop will run in order, and will be repeated for the number of times specified under the /“Count/” condition (Blue). The code for a count-based loop is below:

Next Lesson: Ultrasonic Sensor
Report an issue

chevron_up