top of page
Search

mBot2 Python Line Follower with CyberPi: Step by Step

Oct 13
4 min read

To build an mBot2 line follower in Python, read the Quad RGB sensor's line offset (a number from -100 to 100), turn it into a steering correction, and send different power to the left and right motors many times a second. On the mBot2's CyberPi brain, that takes about 35 lines of Python in mBlock 5. Below is a complete starter program, plus how to tune it so the robot glides along the line instead of wobbling off it.

If you're still deciding which robot to buy, start with our comparison: mBot2 vs micro:bit vs LEGO CS & AI.

What you need

  • A Makeblock mBot2 (CyberPi plus the Quad RGB sensor that comes in the box, plugged into mBuild port 1).

  • mBlock 5 (desktop or web) with the CyberPi device added and set to Upload mode, then switched from Blocks to Python.

  • A line track: black electrical tape on a white floor or poster board works well. Keep curves gentle at first.

  • A calibrated sensor. Calibrate the Quad RGB sensor on your track before you start (Makeblock shows how in its support pages); lighting changes the readings a lot.

How the Quad RGB sensor sees the line

The sensor has four probes in a row, named L2, L1, R1 and R2. Makeblock's Python library gives you two handy readings:

  • get_offset_track(1) returns an integer from -100 to 100. Zero means the line is centered under the sensor. Negative means the sensor has drifted to the left of the line; positive means it has drifted to the right.

  • get_line_sta(1) returns 0 to 15, one bit per probe. A 1 means that probe sees background, so 15 means all four probes see white: the robot has lost the line.

The "1" in both calls is the sensor's index, which is 1 when you only have one Quad RGB sensor connected.

The full mBot2 Python program

Paste this into mBlock 5's Python editor and upload it to CyberPi:

import cyberpi, mbot2, mbuild, time

BASE = 35      # cruising power in percent (try 30-50)
KP = 0.35      # steering gain: how hard to correct per unit of offset
SEARCH = 30    # spin power used when the line is lost
LIMIT = 70     # never command more than this

def clamp(value, low, high):
    return max(low, min(high, value))

cyberpi.console.println("Press A to start")
cyberpi.console.println("Press B to stop")
while not cyberpi.controller.is_press("a"):
    time.sleep(0.02)

last_offset = 0
while not cyberpi.controller.is_press("b"):
    state = mbuild.quad_rgb_sensor.get_line_sta(1)
    if state == 15:
        # All four probes see background: the line is lost.
        # Spin toward the side where we last saw it.
        left = SEARCH if last_offset < 0 else -SEARCH
        right = -left
    else:
        offset = mbuild.quad_rgb_sensor.get_offset_track(1)  # -100..100
        last_offset = offset
        steer = KP * offset
        left = clamp(BASE - steer, -LIMIT, LIMIT)
        right = clamp(BASE + steer, -LIMIT, LIMIT)
    # The right motor is mounted mirrored, so "forward" is negative power.
    mbot2.drive_power(left, -right)
    time.sleep(0.01)

mbot2.EM_stop(port="all")
cyberpi.console.println("Stopped")

We ran this program in a simulator with stand-in hardware functions to check the logic. Real floors, batteries and tape are messier, so expect to tune the numbers on your own track.

How it works, step by step

  1. Wait for button A. The robot sits still until you press A on CyberPi, so it doesn't race off the table while you set it down.

  2. Check if the line is lost. If get_line_sta returns 15, no probe sees the line. The robot spins toward the side where it last saw it, using the sign of the last offset.

  3. Measure the error. Otherwise, get_offset_track tells us how far off-center we are.

  4. Turn error into steering. steer = KP × offset. If the sensor has drifted left (negative offset), the left wheel speeds up and the right wheel slows down, turning the robot back to the right.

  5. Clamp and drive. clamp() keeps power inside safe limits. Because the mBot2's right motor is mounted mirrored, forward on that side is negative power, which is why the code sends -right.

  6. Repeat about 100 times a second until you press B, then EM_stop stops both motors.

This is proportional control, the "P" in PID. It's the same idea we use for driving straight with a gyro on SPIKE Prime: measure an error, multiply by a gain, correct.

Tuning tips

  • Robot steers away from the line? Your sensor or wiring is reversed from ours. Flip the sign of KP (use -0.35).

  • Wobbles side to side? KP is too high. Lower it in small steps (0.35 → 0.25).

  • Runs off on curves? KP is too low or BASE is too fast. Raise KP a little, or drop BASE to 30.

  • Smooth on straights, lost on sharp turns? That's what the search behavior is for. Try a larger SEARCH value, or slow down BASE.

  • Change one number at a time and write down what happened. That habit is half of what robotics teaches.

Want to go further? Adding a derivative term calms the wobble at higher speeds. Our PID line follower guide (Arduino) explains P, I and D in plain language, and the same math drops straight into this mBot2 program.

Common questions

Do kids need to know Python before trying this? No. Many kids build the same logic in mBlock blocks first, then switch to Python. Once the idea makes sense in blocks, the Python version is a short step, and this program is a good first one.

Why not just use the built-in line-follow block? The block works, but writing the loop yourself teaches how sensors, feedback and motors fit together. That understanding carries over to every robot after this one.

Can I use mbot2.forward() instead of drive_power()? forward() moves both wheels at one speed, so it can't steer. Line following needs separate left and right power, which is what drive_power gives you.

Keep learning with Fusion Robotics Education

Our mBot2 Robotics and AI course walks kids through sensors, Python and projects like this one at their own pace. Browse the full course catalog (including free courses), or try everything with All-Access for $39/month with a 7-day free trial. Prefer a live instructor? Remote 1-on-1 lessons are $149/month; text (619) 786-5731 to set one up.

Shopping for a robot first? See the kits our coaches recommend.

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 on their own project. The first session is free: text (619) 786-5731 to book.

 
 
 

Comments


bottom of page