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!
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.
def handle_buttonshould go in the “Define functions” section of your code.
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
But this time, we schedule the next move as an
on_timeoutevent, rather than using
Add the code below to your program.
Put your new function definitions in the “Define Functions” section of your code.
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
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…