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
chassis.forward: 1 is full ahead, −1 full reverse, 0.5 half throttle. There's no sideways throttle.chassis.turn: a fraction of the chassis's top turn rate. On a light chassis that's half a turn (180°) a second. Turn with no throttle and the bot spins on the spot.- Both are commands: they hold until you change them.
- Top speed depends on the machine's mass. The Machine section in Brain code shows your machine's top speed, acceleration and turn rate.
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.