thebotslam

How do I make my bot turn to a heading and drive somewhere?

Bearings

Every angle in the API is a field bearing in degrees: 0 is east, 90 is north, and positive is counter-clockwise (left), from −180 to 180. chassis.heading is the bearing the chassis faces. The scanner's contacts, the laser's aim and the rangefinder's direction all use the same field bearings, so you can compare them with the heading directly.

Turn to a heading, then drive

from bot import Chassis, wait

chassis = Chassis(0)
goal = 90  # face north

while True:
    rel = goal - chassis.heading  # how far off, the short way round
    if rel >= 180:
        rel -= 360
    if rel < -180:
        rel += 360
    chassis.turn = rel / 45                      # full rate 45 degrees or more off
    chassis.forward = 1 if abs(rel) < 20 else 0  # drive once roughly lined up
    wait()

Dividing by 45 gives full turn rate while you're 45° or more off and gentler turning as you line up, so the bot doesn't overshoot. Values beyond −1..1 are clamped.

What the numbers mean

Steering at something you can see

To chase a contact, use its bearing as the goal: goal = scanner.bearing(0). The house bot sweeper does exactly this. Pick it from Start from… in a new Brain code tab to read it.

Driving to a point

To drive to a spot on the field you need to know where you are: carry a GPS (or a radio, which is a GPS too) and read x, y, z = gps.read(). x runs east from the west wall and y north from the south wall, in metres. Turning a spot into a bearing takes some trigonometry, and the Python subset has no maths functions such as sine or arctangent, so write your own approximation. The house bot seeker includes a small sine function you can borrow.