KevsRobots Learning Platform
70% Percent Complete
By Kevin McAleer, 4 Minutes
To prevent collisions with obstacles, use bot.distance to measure the distance between the object and your bot. If the measured distance is less than a specified threshold (e.g., 5 cm), stop the bot and move it backward to maintain a safe distance from the obstacle.
The ultrasonic rangefinder works by sending out sound waves and measuring how long they take to bounce back. The bot.distance property returns the distance in centimeters to the nearest object.
The code:
from burgerbot import Burgerbot
bot = Burgerbot()
while True: # Infinite loop - runs forever (note: capital T in True!)
distance = bot.distance # Get current distance in cm
if distance <= 5: # Object closer than 5cm
print(f"Too close! Distance: {distance}cm")
bot.stop()
bot.backward(1) # Back up for 1 second
else:
print(f"Path clear. Distance: {distance}cm")
bot.forward(0.5) # Move forward in short bursts
How it works:
while True: creates an infinite loop that runs continuouslybot.distance gets the current distance reading from the rangefinderforward(0.5) instead of forward(1) makes the robot check distance more frequentlyWhy short bursts? Moving in 0.5-second intervals allows the robot to respond more quickly to obstacles, making navigation smoother and safer.
bot.distance returns 0 or very large numbers (like 400)Why: Incorrect wiring prevents the sensor from sending or receiving ultrasonic signals
Why: Sound waves need time and space to separate transmission from echo
Why: Soft materials (like fabric) and dark surfaces absorb sound waves instead of reflecting them
while True: with a capital T. Python is case-sensitive!Why: while true: will cause a NameError because true is not defined in Python (itβs True)
Ready to experiment with object avoidance? Try these challenges:
Adjust the detection threshold: Change if distance <= 5: to if distance <= 10:. How does the robotβs behavior change? What about distance <= 3?
Add turning: Modify the code to turn left or right after reversing. Hint: Add bot.left(0.5) after the backward command.
Variable speed: Make the robot slow down as it approaches objects. Use the distance value to calculate motor speed.
Obstacle counter: Keep track of how many objects the robot has avoided. Print this count to the console.
Advanced Challenge: Create a robot that maintains exactly 10cm from a wall as it drives parallel to it. Youβll need to constantly adjust direction based on distance readings!
To maintain a consistent distance from an object, first measure the distance between the object and your position. Move forward until the object is at the desired distance, then stop. If the object is closer than the desired distance, move backward until the desired distance is achieved. This process allows you to effectively follow an object while maintaining a set distance from it.
You can use the arrows β β on your keyboard to navigate between lessons.
Comments