thebotslam

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

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:

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.