Get Moving

When you see CodeBot, you can tell right away it’s eager to show off how those motors and wheels work!

Warning

In the following steps, be careful as you run your programs! You’ll need some space to let the ‘bot move around. Also, it’s helpful if your USB cable is long enough to allow a bit of movement.

Of course, your programs can run without the USB cable attached, so feel free to unplug after loading the code onto the ‘bot.

1. Power up a wheel

Enter the following code in CodeSpace to get the LEFT wheel running:

from botcore import *
import time

motors.enable(True)

# Run LEFT motor at 50% power forward for 1 second
motors.run(LEFT, 50)
time.sleep(1.0)

motors.enable(False)

2. Spin in place

The following shows off rotation:

from botcore import *
import time

motors.enable(True)

# Run LEFT motor forward and RIGHT motor backward for 1 second
motors.run(LEFT, 50)
motors.run(RIGHT, -50)
time.sleep(1.0)

motors.enable(False)

3. Drive in a SQUARE

Can you make CodeBot drive in a square?

The code below starts by defining two functions:
  • go_straight() drives in a straight line for one second.

  • turn_right() rotates to the right (clockwise) for half a second.

Take a look at the code below before you run it.
  • How long will the sides of the square be?

  • Will the ‘bot turn proper (90 °) corners?

Note

As you might guess, using motor power levels and time delays is not a very precise way to move the ‘bot. You will need to adjust power levels and time durations to make your square nice and neat.

from botcore import *
import time

def go_straight():
    # Forward 1 sec
    motors.run(LEFT,  50)
    motors.run(RIGHT, 50)
    time.sleep(1.0)

def turn_right():
    # Rotate right (try for 90 deg)
    motors.run(LEFT,  +20)
    motors.run(RIGHT, -20)
    time.sleep(0.5)

motors.enable(True)

# Loop 4 times. A square has 4 sides, right?
for i in range(4):
    go_straight()
    turn_right()

motors.enable(False)

4. Challenge

Consider what you learned in Lights On.

Can you blink an LED every second while driving in a square at the same time?

This sort of multitasking can be challenging when using the time.sleep methods we’ve shown so far. That’s because sleep() is a blocking function - meaning your code has to wait until the sleep is over before doing anything else.

The next lesson introduces an awesome method to overcome this problem: event-driven programming!