For this activity, you will need both of your front IR sensors. This time, instead of stopping and waiting for the obstacle to be removed, you will tell Zumi to turn a little to the left or to the right to go around, depending on which sensor is triggered.
Initialize heading
In the beginning of the program, set your heading to 0. You can create a variable with a different name, like angle or direction, but we will use heading in this example. The reason you will be using a variable is because your direction will constantly be changing depending on what obstacles get in Zumi’s way!
heading=0
For all of our programs, it is very important to set the heading to zero to make sure you start off going straight!
Change heading
For this mission, your goal is to turn a little to the left if your right sensor is triggered, and a little to the right if your left sensor is triggered. If both sensors are triggered, something is directly in front! Zumi will need to do a complete 180 to avoid what could possibly be a dead end. Instead of calling turn_left() or turn_right(), you will instruct Zumi to change heading by adding or subtracting degrees. For example:
if front_right_ir < 100:
heading = heading + 30
Since the right sensor being triggered means we go left, you need to add degrees, not subtract. Look back to the lesson gyroscopes if you need help remembering absolute angles.
Pseudocode
set heading to zero
check IR sensors
if front right sensor is triggered, change heading by positive degrees to go left
else if front left sensor is triggered, change heading by negative degrees to go right
else if both sensors are triggered, stop, reverse a little bit, and change heading by 180 (positive or negative)
keep going straight with the new heading
repeat!
Logical operators
Before you go into writing your code, notice that the third if statement is checking if both are triggered. In Python, you would use the and operator, just like in English!
if front_right_ir < 100 and front_left_ir < 100:
# Write code here to stop, reverse, and change directions by 180
In [ ]:
# Write out your code here!
heading = 0
zumi.reset_gyro()
for x in range(1000):
# Statements
zumi.stop()