SPIKE Prime Line Follower: Proportional Line Following in Python (Full Code)
A SPIKE Prime line follower uses one color sensor to watch the edge of a black line and steers the robot a little left or right, many times a second, to stay on that edge. The smoothest way to do it is proportional control: the further the sensor drifts from the edge, the harder the robot turns back. Below is how it works, a complete SPIKE App 3 Python program you can copy, and the tuning steps that make it reliable.
Why follow the edge, not the line
A color sensor pointed at the mat reports reflected light as a number: low over black, high over white. If the sensor sits in the middle of a thick black line, it reads "black" whether the robot is slightly left or slightly right, so the robot can't tell which way to correct.
The edge is different. Halfway between black and white, the reading changes smoothly as the sensor moves. A little more white means the robot has drifted off the line; a little more black means it has drifted onto it. That gives the program a clear direction to steer, which is why almost every good line follower tracks one edge of the line.
What you need
A two-wheel drive base with one motor per wheel. The program assumes the left motor is on port A and the right motor on port B.
One color sensor on port C, mounted at the front center, facing down, about 1–2 cm above the mat. Mounting it well ahead of the wheels makes steering smoother.
Your own reflection readings. Hold the sensor over black and over white and note the numbers. Lighting changes from room to room, so re-check before a competition.
How proportional line following works
Every 10 milliseconds the program repeats the same four steps:
Read the reflected light from the color sensor.
Work out the error: the reading minus the edge value (halfway between black and white).
Multiply the error by a constant, KP, to get a turn amount.
Speed up one wheel and slow the other by that turn amount.
Small errors give gentle corrections and big errors give strong ones. Compare that with the simplest "bang-bang" follower (turn left if dark, turn right if light), which zig-zags constantly because it always corrects at full strength. Proportional control is the same idea we used for keeping a robot pointed straight in Drive Straight with a Gyro, just with light instead of an angle.
The SPIKE Prime Python code
This uses the SPIKE App 3 Python modules (motor, color_sensor and runloop). We ran the logic in a simple simulator with the hardware functions stubbed out, and the simulated robot settled onto the edge and stopped at the target distance. Tune the numbers on your own robot.
from hub import port
import motor, color_sensor, runloop
LEFT_MOTOR, RIGHT_MOTOR = port.A, port.B
SENSOR = port.C # one color sensor, front center, facing down
LEFT_DIR, RIGHT_DIR = -1, 1 # flip a sign if a wheel spins backward
BLACK = 15 # measure on your own mat
WHITE = 95
EDGE = (BLACK + WHITE) // 2 # target: the edge of the line
KP = 3 # steering strength (deg/s per point of error)
def drive(left_speed, right_speed):
motor.run(LEFT_MOTOR, int(left_speed) * LEFT_DIR)
motor.run(RIGHT_MOTOR, int(right_speed) * RIGHT_DIR)
def stop():
motor.stop(LEFT_MOTOR)
motor.stop(RIGHT_MOTOR)
def distance_degrees():
# average wheel rotation since the last reset, in degrees
left = abs(motor.relative_position(LEFT_MOTOR))
right = abs(motor.relative_position(RIGHT_MOTOR))
return (left + right) // 2
async def follow_line(degrees, speed=250, edge_side=1):
# edge_side = 1 follows the right edge of the line, -1 the left edge
motor.reset_relative_position(LEFT_MOTOR, 0)
motor.reset_relative_position(RIGHT_MOTOR, 0)
while distance_degrees() < degrees:
error = color_sensor.reflection(SENSOR) - EDGE
turn = KP * error * edge_side
drive(speed + turn, speed - turn)
await runloop.sleep_ms(10)
stop()
async def main():
await follow_line(1440) # about 4 wheel rotations
runloop.run(main())Two settings do most of the work. edge_side chooses which edge to follow: 1 for the right edge, -1 for the left. If your robot spins away from the line instead of toward it, flip this value. degrees sets how far to follow, measured in wheel rotation (360 degrees is one full turn of the wheel), so the robot stops at a repeatable spot.
Tuning your line follower
Start slow. Use a speed around 150–250 degrees per second while you tune, then speed up once it's steady.
Robot wobbles side to side? Lower KP a little at a time.
Robot drifts off on curves? Raise KP, or slow down before tight curves.
Wheel spins backward? Flip the sign of LEFT_DIR or RIGHT_DIR. On most drive bases one motor is mounted mirrored.
Change one thing at a time. Write down each KP and speed you try and what happened. It turns guessing into testing.
When proportional control feels easy, the next step is PID, which adds memory of past errors and a prediction of where the error is heading. Our post on how a line-following robot works with PID explains those extra terms.
Using line following in FLL runs
On a robot game table, line following is most useful for getting to a model along a known path, especially when the start of a run varies a little. A reliable pattern is: follow a line for a set distance, then square on a line or use a gyro turn to line up for the mission. Breaking a long run into short, landmark-based pieces is one of the best ways to make every run repeatable.
Record your reflection values, KP and test results in your engineering notebook. Judges like seeing a team measure, adjust and improve.
Common questions
Do I need two color sensors to follow a line?
No. One sensor following one edge works well for most paths. Teams often add a second sensor for squaring on lines or spotting intersections, but it isn't needed to follow a line.
Is SPIKE Prime still worth learning now that it's retired?
Yes. LEGO Education retired SPIKE in June 2026, but SPIKE robots can still be used in the 2026–27 BIOGLOW season, and FIRST has said its next K–8 programs stay compatible with SPIKE through 2028–29. Proportional control works the same way on any robot.
Why does my follower work at home but not on the competition table?
Usually lighting or the mat's print. Re-measure black and white on the real table during practice time and update BLACK and WHITE.
Learn this with Fusion Robotics Education
Sensors, proportional control and reliable autonomous code are what our courses teach step by step. Start with the LEGO SPIKE Prime course (grades 4–8) or the free FLL Competition-Ready course, and browse the full catalog of online courses.
Free self-paced courses to get started.
All-Access for $39/month, with a 7-day free trial.
Remote 1-on-1 live lessons with a coach for $149/month (text (619) 786-5731).
In San Diego? Our weekend group sessions in Scripps Ranch are 1.5 hours a week for ages 6–18, with at most 10 kids and every child working on their own project at their own pace. Your first session is free: text (619) 786-5731 to book it.



Comments