Loops help robots repeat actions without needing the same commands written over and over. In robot programming, a loop can make a robot drive forward, check a sensor, turn, and then do those steps again. This is useful because many robot tasks use patterns, such as driving in a square or following a line.
Learning loops makes programs shorter, easier to read, and easier to fix.
Key Facts
- A loop repeats a set of commands until a count or condition tells it to stop.
- To drive in a square, a robot can repeat 4 times: drive forward, then turn 90 degrees.
- Square path rule: total turn = 4 x 90 degrees = 360 degrees.
- Repeat loops use a counter, such as repeat 4 times, to control how many cycles run.
- Sensor checks inside a loop let a robot react while it repeats, such as stopping if an obstacle is close.
- Python-style pseudocode for a square path: for i in range(4): drive_forward(); check_sensor(); turn_right(90)
Vocabulary
- Loop
- A loop is a programming structure that repeats a group of commands.
- Repeat block
- A repeat block is a visual coding block that runs the commands inside it a set number of times.
- Counter
- A counter is a value that keeps track of how many times a loop has repeated.
- Sensor
- A sensor is a device that lets a robot detect information from its surroundings, such as distance, light, or touch.
- Pseudocode
- Pseudocode is a simple way to write program logic in plain language or code-like steps before using a real programming language.
Common Mistakes to Avoid
- Putting only the drive command inside the loop is wrong because the robot will keep moving straight instead of making a square.
- Using repeat 3 times for a square is wrong because a square has 4 sides and needs 4 repeated movements.
- Turning 45 degrees at each corner is wrong because a square path needs a 90 degree turn at each corner.
- Forgetting to check the sensor inside the loop is wrong because the robot may not react to obstacles while it is repeating the path.
Practice Questions
- 1 A robot needs to drive in a square. Each side is 50 cm long and each turn is 90 degrees. Write the repeated steps and state how many times the loop should repeat.
- 2 A robot repeats this loop 4 times: drive forward 30 cm, then turn right 90 degrees. What total distance does it drive, and what is the total amount it turns?
- 3 A robot uses a loop that says: drive forward, check distance sensor, turn right, repeat 4 times. Explain why placing the sensor check inside the loop is better than checking the sensor only once before the loop starts.