Module 8 - Section 4 - Events and decisions
Module 8 - Section 4 - Events and decisions
- review Edpy code for various events handling
- create code to detect obstacles using Edison robot sensors
- extend the code to avoid obstacles
8.4.2 - Event Handling
Write the following program to have the Edison robot continuously drive and avoid obstacles.
#-------------Setup----------------
import Ed
Ed.EdisonVersion = Ed.V2
Ed.DistanceUnits = Ed.CM
Ed.Tempo = Ed.TEMPO_MEDIUM
#--------Your code below-----------
#turn on obstacle detection
Ed.ObstacleDetectionBeam(Ed.ON)
Ed.RegisterEventHandler(Ed.EVENT_OBSTACLE_AHEAD, "avoidObstacle")
Ed.Drive(Ed.FORWARD, Ed.SPEED_5, Ed.DISTANCE_UNLIMITED)
while True:
pass
def avoidObstacle():
Ed.Drive(Ed.SPIN_RIGHT,Ed.SPEED_5,180)
Ed.Drive(Ed.FORWARD, Ed.SPEED_5, 10)
You can download the code from here
This program uses Python Event Handling. In event handling, certain events, such as an obstacle being detected, are registered with the program along with an associated function and then when these events occur the associated functions are called. The associated functions are called event handlers and they act as an interrupt, which means when the event occurs, the main program is paused while the given function is run.
In our example above, the obstacle-detected-ahead event is registered in line 13 using RegisterEventHandler. The first parameter is the event that is going to occur and the second parameter is the function that will be called when the event occurs. Thus, when an obstacle is detected ahead the avoidObstacle function will be called.
Describe what the robot does.