In this challenge, students will use the ultrasonic sensor to detect obstacles in front of the robot and program it to avoid them by stopping and turning away.
- My robot drives forward until it detects an obstacle within 300mm.
- My robot stops before hitting the obstacle.
- My robot turns (left or right) to avoid the obstacle, then continues driving forward.
- Complete Module 8: Functions, fills, and pizza!
- Complete Blockly Levels 7 & Blockly Levels 9 to apply the algorithm visually.
flowchart TD
A[Start Program] --> B[Setup Robot and Variables]
B --> C{Main Control Loop}
C --> D[Read Distance from Ultrasonic Sensor]
D --> E{Is distance valid and less than safe_distance?}
E -->|Yes| F[Apply Brake]
F --> G[Turn Left]
G --> C
E -->|No| H[Drive Forward]
H --> C
style A fill:#e1f5fe,color:#000000
style B fill:#000000,color:#ffffff
style C fill:#fff3e0,color:#000000
style D fill:#e3f2fd,color:#000000
style E fill:#ffecb3,color:#000000
style F fill:#ffcdd2,color:#000000
style G fill:#e1bee7,color:#000000
style H fill:#e8f5
- Set up your robot and connect to the coding environment as before.
Write code so your robot:
- Drives forward.
- Uses the ultrasonic sensor to check for obstacles.
- If an obstacle is detected within 300mm, the robot stops, turns, and continues forward.
from aidriver import AIDriver, hold_state
import aidriver
aidriver.DEBUG_AIDRIVER = True
my_robot = AIDriver()
my_counter = 0
wheel_speed = 200
speed_adjust = 0
turn_speed = 200
turn_time = 0
safe_distance = 0
def turn_left():
# implement 90 degree left turn here
pass
def drive_forward():
# implement drive forward here
pass
def brake():
my_robot.brake()
hold_state(3)
while True:
distance = my_robot.read_distance()
if distance != -1 and distance < safe_distance:
brake()
turn_left()
else:
drive_forward()If you get an error when running this, or the names don’t match the AIDriver functions, see Common_Errors.md.
- Test and adjust the distance threshold and turn timing as needed.
- Try different turn directions or randomize the turn for more advanced behaviour.
- Copy all your code from
main.py. - Paste it in your portfolio under "Challenge 5".
-
First, make the robot just drive forward and print the distance:
print("distance:", my_robot.read_distance())
-
Once that works, add the
if/elsedecision to brake and turn. -
Run your program after every small change so you know which edit caused an error.
-
If behaviour is confusing, add
print("HERE 1"),print("HERE 2")inside different branches to see which path the code is taking.