Robotics-II-Circuit-Python

Circuit Python tutorials in Robotics II

View the Project on GitHub MrPrattASH/Robotics-II-Circuit-Python

Table of Contents

Forever Loops

Video Tutorial


Text Tutorial

In robotics, we always run our programs forever, using iteration, or a loop.

In this first tutorial, we’ll learn:

Let’s try the difference between these 2 programs

Single Line Program

  1. Connect the M4 to your computer, and load code.py
  2. On line 1, write ` print(“this is a non-looped program)`
  3. Open the serial console.
  4. Save this program and observe the serial output

While True

  1. delete all existing code.
  2. write in this code:
import time

while True:
    print("this is in a loop!")
    time.sleep(1)

  1. Open the serial console
  2. Save this program and observe the serial output.

Examining a While True Loop:

You’ve likely noticed by now that rather than printing the statement once, it will print forever, in a loop! That’s what the “while True:” statement does. Let’s examine this:

import time

print("this is before the loop")
while True:
    print("this is inside the loop")
    print("Still inside the loop")
    time.sleep(1)
print("this is NOT indented, so it is outside the loop")
print("the statement directly above, and this statement, will NEVER print")

Key Takeaways

All of our robotics programs will have a single while True: loop inside of them, and this is where all of our code will run. Much like a robot vacuum, we want our robot following instructions forever, until it is powered off.