Walk and Chew Gum

Challenge: Show that CodeBot can walk and chew gum at the same time!
  • Drive CodeBot in a SQUARE pattern, while blinking an LED 10x per second.

Remember the multitasking challenge posed at the end of Get Moving? Now you’re ready to tackle it!

1. Blinking the LED

The first part is simple - it’s just our previous Blink Forever example:

from botcore import *
from botservices import BotServices
bot = BotServices()

# ---- Define functions ----
def led_on():
    leds.user_num(0, True)
    bot.on_timeout(led_off, 1000)

def led_off():
    leds.user_num(0, False)
    bot.on_timeout(led_on, 1000)

# ---- Setup events ----

# Turn LED on and schedule led_off for later.
led_on()

# ---- Start the event-loop ----
bot.loop()

2. Add a “kill switch”

Before we get this thing moving, it would be nice to have a way to stop.
Add the code below to your program.
  • The def handle_button should go in the “Define functions” section of your code.

  • The bot.on_button(handle_button) must be called before the event-loop is started.

def handle_button(buttons):
    # If any button is pressed, stop
    motors.enable(False)   # Kill the motors
    bot.stop()   # Exit the event loop


# Hook-in the button handler function
bot.on_button(handle_button)

3. Add the motors

Next we define functions to go_straight() and turn_right().

But this time, we schedule the next move as an on_timeout event, rather than using sleep()!

Add the code below to your program.

  • Put your new function definitions in the “Define Functions” section of your code.

  • The motors.enable() and go_straight() calls must come before the event-loop is started.

Can you see how just one call to go_straight() causes a chain reaction?

def go_straight():
    # Move forward a little, then schedule right turn
    motors.run(LEFT,  50)
    motors.run(RIGHT, 50)
    bot.on_timeout(turn_right, 1000)

def turn_right():
    # Rotate right (try for 90 deg), then schedule a go_straight()
    motors.run(LEFT,  +30)
    motors.run(RIGHT, -30)
    bot.on_timeout(go_straight, 500)

# Start making our square!
motors.enable(True)
go_straight()

Mission accomplished! That’s all the code you needed to move in a square forever while blinking.

When your robot needs to act based on time, remember on_timeout events!

Be the Bot

Can you put yourself in CodeBot’s shoes, er, … wheels ?

With event-driven coding, it’s helpful to ask “If I was CodeBot, what would I do next?” Sometimes your next move depends only on the passage of time. But more often there are other “external events” that move you along. You might sit quietly until someone presses your buttons! CodeBot has other sensors too, like proximity, accelerometer, and line sensors. Using event callbacks your code can make the ‘Bot react to all of its senses!

Next lesson will explore using the Line Sensors