How do I keep my bot from driving into walls and obstacles?
Look ahead, and notice when you're stuck
This bot carries a rangefinder on channel 1 and a GPS on channel 3:
from bot import Chassis, Rangefinder, Gps, wait
chassis = Chassis(0)
rangefinder = Rangefinder(1)
gps = Gps(3)
wait() # start on a fresh tick, with real readings
px, py, pz = gps.read()
stuck = 0
back = 0
while True:
x, y, z = gps.read()
rangefinder.bearing = chassis.heading # look straight ahead
if back > 0:
back -= 1 # backing off: reverse, turning
chassis.forward = -1
chassis.turn = 1
elif rangefinder.hit and rangefinder.range < 4:
chassis.forward = 0.2 # something close ahead: turn away
chassis.turn = 1
stuck = 0
else:
chassis.forward = 1
chassis.turn = 0
# Full throttle, yet hardly moving: pushing on something.
if abs(x - px) + abs(y - py) < 0.05:
stuck += 1
else:
stuck = 0
if stuck > 10:
back = 20 # a second of backing off
stuck = 0
px = x
py = y
wait()
Use the channels your own machine shows under Machine in Brain code.
The rangefinder
rangefinder.bearing = degpoints it along a field bearing. It holds while the chassis turns.rangefinder.hitis true when something is within 30 m along that bearing.rangefinder.rangeis the distance in metres from the centre of your bot to the first surface: a wall, a block or another bot's hull. It's 0 when nothing is in range, so checkhitfirst.- A new bearing's reading comes in after the next
wait().
The GPS
x, y, z = gps.read() gives your position in metres: x runs east from the west wall (0 to 96) and y north from the south wall (0 to 54). So you can keep clear of the edges with plain comparisons, such as backing off when x > 88. A radio (RAD-1) reads your position the same way with radio.read().
Without extra parts
With only a scanner, you still have clues:
- Walls and block faces line up with the field, so a contact at almost exactly 0, 90, −90 or −180 degrees is usually one of them.
- A contact that never moves is an obstacle. Remember where it is and steer round it.
Rough ground
Some ground slows you down (mud, sand, oil), and some slopes are too steep to climb. Every chassis has a built-in traction sensor and incline sensor (no part needed) that tell you how well the ground grips and how steep it is. See the Reference in Brain code for how to read them in your language.