Line follower — Smart Car (Python, four files)
This example is written twice, once for each firmware. Pick the tab that matches the firmware of your Smart Car: the tab you pick is remembered on the other examples.
Firmware 3.0 renamed the Python names a program writes, and kept none of the old ones: a Smart Car on 2.x does not know the 3.0 names, and a Smart Car on 3.0 does not know the 2.x ones. The name map lists every change. If you open the example from inside MoBot, it picks the version for the firmware of your Smart Car. If you download a file from this page, use the one in the tab for your firmware.
The robot follows a black line on the floor. This is one of the two examples in the set that are split into more than one file, and that is the point: a real program grows until one file is too big to think about.
| file | what lives in it |
|---|---|
main.py |
the rules: look, decide, drive, repeat |
eyes.py |
reading the five sensors and turning them into one number |
wheels.py |
straight, nudge, spin, stop |
settings.py |
every number you will want to change, and nothing else |
When the robot swings too wildly you open settings.py, change SPEED, and the
other three files are still right. That is the whole idea.
This is the version for a robot on firmware 3.0. For a robot that still runs firmware 2.x, MoBot opens the 2.x version of this example instead.
Project for firmware 3.0: 07-line-follower.firmware-3.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A Smart Car with the five IR sensors fitted underneath, on its battery.
- A line to follow: black electrical tape on a light floor, about 2 cm wide. Make a big loop with gentle corners to start with.
- Nothing plugged into the joystick sockets — see the warning below.
How to run it — read this bit
Section titled “How to run it — read this bit”MoBot saves one file at a time: the tab you are looking at. So:
- Open 07-line-follower.firmware-3.mobot. You will see four tabs.
- Click the
settings.pytab and press Save. - Click
eyes.pyand press Save. - Click
wheels.pyand press Save. - Click
main.pyand press Save — last, because it is the one the robot runs when it starts. Savingmain.pyalso starts the program. - Put the robot on the line during the three-second countdown, or unplug it and switch it on again to start from the beginning.
If you forget one of the middle three, the robot will stop straight away with
ImportError: no module named 'wheels' in the monitor. That message is telling
you exactly which tab you did not save.
What you should see and hear
Section titled “What you should see and hear”| when | what |
|---|---|
| at the start | both LEDs on for three seconds — that is your countdown to put the robot down |
| following | the robot drives along the tape, wiggling slightly |
| drifting left | LED 1 lights — it is steering back to the right |
| drifting right | LED 2 lights |
| twice a second | a line like eyes: middle steer: 0 in the monitor |
| off the end of the tape | lost the line - hunting, both LEDs on, and the robot spins on the spot looking for it |
| still lost after 1.5 s | it stops and plays a short three-note error buzz |
If it follows the wrong thing
Section titled “If it follows the wrong thing”If the robot carefully follows the floor instead of the tape, your IR board
reads the opposite way round from the one this program assumes. Open
settings.py, change LINE_READS = 1 to LINE_READS = 0, save that one tab
again, and start the program again. Nothing else needs to change — which is exactly why that number
lives in its own file.
The trap this example exists to show
Section titled “The trap this example exists to show”main.py gets the robot for free. Your own files do not.
The robot puts the name robot into main.py’s world while it is switching on.
It does not do that for eyes.py or wheels.py. A helper file that just
says robot.line_sensor fails with:
NameError: name 'robot' isn't definedThe fix is one line at the top of each of your own files:
from smart_car import robotThat is not a copy of the robot — it is the very same one. (On a Mini the line
is from smart_car_mini import robot.)
The program
Section titled “The program”This project has 4 files. Each one is a tab in MoBot. The code below is a reading copy of each: editing it changes nothing, so open the project and edit it there.
# main.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.# Written for firmware 3.0; the 2.x version is 07-line-follower.main.py.
"""Line follower - MoBot Smart Car. A program in FOUR files.
main.py this file: the rules of the game eyes.py reads the five sensors underneath wheels.py makes the robot go settings.py all the numbers you will want to change
Splitting a program up is not showing off. It means that when the robot swingstoo wildly on the corners you open settings.py, change one number, and everyother file carries on being right.
IMPORTANT: save ALL FOUR files to the robot. In Python mode MoBot saves thetab you are looking at, one at a time - so click each tab and press Save."""
import time
import settingsimport eyesimport wheels
led1 = robot.led1 # main.py gets the robot for free...led2 = robot.led2 # ...the other three files have to ask for it
def hunt(last_direction, deadline): """We lost the line. Spin the way we last saw it going and look for it.""" if last_direction < 0: wheels.spin_left() else: wheels.spin_right() return time.ticks_diff(deadline, time.ticks_ms()) > 0
print("Line follower. Put the robot on the black line.")print("Starting in 3 seconds...")led1.on()led2.on()time.sleep(3)led1.off()led2.off()
last_direction = 1 # which way we last saw the line golost_deadline = None # when to give up huntingreport = 0
while True: seen = eyes.look() direction = eyes.steer(seen)
if direction is None: # Lost. if lost_deadline is None: lost_deadline = time.ticks_add(time.ticks_ms(), int(settings.LOST_SECONDS * 1000)) print("lost the line - hunting") if not hunt(last_direction, lost_deadline): wheels.halt() print("Cannot find the line. Stopping.") robot.buzzer.play_song("0 F4 1 0;1 F4 1 0;2 F4 2 0") break led1.on() led2.on() else: lost_deadline = None if direction != 0: last_direction = direction
if direction == 0: wheels.straight() elif direction == -1: wheels.nudge_left() elif direction == 1: wheels.nudge_right() elif direction == -2: wheels.spin_left() else: wheels.spin_right()
# The LEDs are a steering indicator you can watch from across the room. led1.set(1 if direction < 0 else 0) led2.set(1 if direction > 0 else 0)
report = report + 1 if report % 25 == 0: # about twice a second, not 50 times print("eyes:", eyes.describe(seen), " steer:", direction)
time.sleep(settings.LOOP_DELAY)# eyes.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""eyes.py - the five sensors underneath, turned into one useful number.
READ THIS BIT. It is the whole reason this example has four files.
main.py can say `robot` without importing anything, because the robot putsthat name into main.py's world while it is switching on. Your OWN files do notget that gift. If this file just said `robot.line_sensor` it would fail with:
NameError: name 'robot' isn't defined
So every file you write yourself has to ask for the robot by name, once, at thetop - and that is what the line below does. It is not a copy of the robot; itis the very same one main.py is using."""
from smart_car import robotimport settings
# What the five eyes are called, left to right, for printing.NAMES = ("far left", "left", "middle", "right", "far right")
def look(): """Read all five eyes.
Returns a list of five True/False values, left to right. True means "this eye can see the black line". """ raw = robot.line_sensor.read() return [value == settings.LINE_READS for value in raw]
def steer(seen): """Turn what the eyes saw into ONE number.
-2 the line is far off to the left +2 far off to the right -1 slightly left +1 slightly right 0 straight ahead, well done None no eye can see the line at all - we are lost """ if seen[2]: return 0 if seen[1]: return -1 if seen[3]: return 1 if seen[0]: return -2 if seen[4]: return 2 return None
def describe(seen): """A human-readable version, for the serial monitor.""" lit = [NAMES[i] for i in range(5) if seen[i]] if not lit: return "nothing" return " + ".join(lit)# wheels.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""wheels.py - the six things this robot's wheels can do.
Same rule as eyes.py: this file has to ask for the robot by name."""
from smart_car import robotimport settings
def straight(): robot.left_motor.forward(settings.SPEED) robot.right_motor.forward(settings.SPEED)
def nudge_left(): """Slow the left wheel down so the robot leans left.""" robot.left_motor.forward(settings.SPEED // 3) robot.right_motor.forward(settings.TURN_SPEED)
def nudge_right(): robot.left_motor.forward(settings.TURN_SPEED) robot.right_motor.forward(settings.SPEED // 3)
def spin_left(): """Turn on the spot: left wheel backwards, right wheel forwards.""" robot.left_motor.backward(settings.HARD_TURN_SPEED) robot.right_motor.forward(settings.HARD_TURN_SPEED)
def spin_right(): robot.left_motor.forward(settings.HARD_TURN_SPEED) robot.right_motor.backward(settings.HARD_TURN_SPEED)
def halt(): """Stop: both wheels let go and roll to a halt.""" robot.left_motor.stop() robot.right_motor.stop()# settings.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""settings.py - every number you might want to change, in one place.
Nothing in here does anything. It is just a list of choices, so that when therobot cuts the corners too fast you know exactly which line to edit, and you donot have to hunt through the program looking for a 40."""
# How fast, from 0 to 100.SPEED = 40 # going straightTURN_SPEED = 45 # a small correctionHARD_TURN_SPEED = 55 # the line is right at the edge - lean on it
# What one eye reads when it is over the BLACK line.# If your robot follows the white floor instead of the black tape, change this# to 0 and try again. Different IR boards are wired the opposite way round.LINE_READS = 1
# When every eye has lost the line, spin and hunt for it for this long,# then give up and stop.LOST_SECONDS = 1.5
# How long to rest between decisions. Smaller = twitchier.LOOP_DELAY = 0.02Try changing it
Section titled “Try changing it”SPEED = 55and see where it starts cutting corners.- Make
LOST_SECONDSbig and watch it hunt for ages before giving up. - Add a
sound.pyfile of your own with acelebrate()function, and call it frommain.pywhen the robot has followed the line for 30 seconds.
The robot follows a black line on the floor. This is the only example in the whole set that is split into more than one file, and that is the point: a real program grows until one file is too big to think about.
| file | what lives in it |
|---|---|
main.py |
the rules: look, decide, drive, repeat |
eyes.py |
reading the five sensors and turning them into one number |
wheels.py |
straight, nudge, spin, stop |
settings.py |
every number you will want to change, and nothing else |
When the robot swings too wildly you open settings.py, change SPEED, and the
other three files are still right. That is the whole idea.
Project for firmware 2.x: 07-line-follower.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A Smart Car with the five IR sensors fitted underneath, on its battery.
- A line to follow: black electrical tape on a light floor, about 2 cm wide. Make a big loop with gentle corners to start with.
- Nothing plugged into the joystick sockets — see the warning below.
How to run it — read this bit
Section titled “How to run it — read this bit”MoBot saves one file at a time: the tab you are looking at. So:
- Open 07-line-follower.mobot. You will see four tabs.
- Click the
settings.pytab and press Save. - Click
eyes.pyand press Save. - Click
wheels.pyand press Save. - Click
main.pyand press Save — last, because it is the one the robot runs when it starts. Savingmain.pyalso starts the program. - Put the robot on the line during the three-second countdown, or unplug it and switch it on again to start from the beginning.
If you forget one of the middle three, the robot will stop straight away with
ImportError: no module named 'wheels' in the monitor. That message is telling
you exactly which tab you did not save.
What you should see and hear
Section titled “What you should see and hear”| when | what |
|---|---|
| at the start | both LEDs on for three seconds — that is your countdown to put the robot down |
| following | the robot drives along the tape, wiggling slightly |
| drifting left | LED 1 lights — it is steering back to the right |
| drifting right | LED 2 lights |
| twice a second | a line like eyes: middle steer: 0 in the monitor |
| off the end of the tape | lost the line - hunting, both LEDs on, and the robot spins on the spot looking for it |
| still lost after 1.5 s | it stops and plays a short three-note error buzz |
If it follows the wrong thing
Section titled “If it follows the wrong thing”If the robot carefully follows the floor instead of the tape, your IR board
reads the opposite way round from the one this program assumes. Open
settings.py, change LINE_READS = 1 to LINE_READS = 0, save that one tab
again, and start the program again. Nothing else needs to change — which is exactly why that number
lives in its own file.
The trap this example exists to show
Section titled “The trap this example exists to show”main.py gets the robot for free. Your own files do not.
The robot puts the name mobotROBOTICS into main.py’s world while it is
switching on. It does not do that for eyes.py or wheels.py. A helper file
that just says mobotROBOTICS.irs fails with:
NameError: name 'mobotROBOTICS' isn't definedThe fix is one line at the top of each of your own files:
from startup import mobotROBOTICSThat is not a copy of the robot — it is the very same one. (On a Mini the line
is from startup import mobotMINI.)
The program
Section titled “The program”This project has 4 files. Each one is a tab in MoBot. The code below is a reading copy of each: editing it changes nothing, so open the project and edit it there.
# main.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.
"""Line follower - MoBot Smart Car. A program in FOUR files.
main.py this file: the rules of the game eyes.py reads the five sensors underneath wheels.py makes the robot go settings.py all the numbers you will want to change
Splitting a program up is not showing off. It means that when the robot swingstoo wildly on the corners you open settings.py, change one number, and everyother file carries on being right.
IMPORTANT: save ALL FOUR files to the robot. In Python mode MoBot saves thetab you are looking at, one at a time - so click each tab and press Save."""
import time
import settingsimport eyesimport wheels
led1 = mobotROBOTICS.led1 # main.py gets the robot for free...led2 = mobotROBOTICS.led2 # ...the other three files have to ask for it
def hunt(last_direction, deadline): """We lost the line. Spin the way we last saw it going and look for it.""" if last_direction < 0: wheels.spin_left() else: wheels.spin_right() return time.ticks_diff(deadline, time.ticks_ms()) > 0
print("Line follower. Put the robot on the black line.")print("Starting in 3 seconds...")led1.on()led2.on()time.sleep(3)led1.off()led2.off()
last_direction = 1 # which way we last saw the line golost_deadline = None # when to give up huntingreport = 0
while True: seen = eyes.look() direction = eyes.steer(seen)
if direction is None: # Lost. if lost_deadline is None: lost_deadline = time.ticks_add(time.ticks_ms(), int(settings.LOST_SECONDS * 1000)) print("lost the line - hunting") if not hunt(last_direction, lost_deadline): wheels.halt() print("Cannot find the line. Stopping.") mobotROBOTICS.buzzer.play("0 F4 1 0;1 F4 1 0;2 F4 2 0", looping=False) break led1.on() led2.on() else: lost_deadline = None if direction != 0: last_direction = direction
if direction == 0: wheels.straight() elif direction == -1: wheels.nudge_left() elif direction == 1: wheels.nudge_right() elif direction == -2: wheels.spin_left() else: wheels.spin_right()
# The LEDs are a steering indicator you can watch from across the room. led1.setState(1 if direction < 0 else 0) led2.setState(1 if direction > 0 else 0)
report = report + 1 if report % 25 == 0: # about twice a second, not 50 times print("eyes:", eyes.describe(seen), " steer:", direction)
time.sleep(settings.LOOP_DELAY)# eyes.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""eyes.py - the five sensors underneath, turned into one useful number.
READ THIS BIT. It is the whole reason this example has four files.
main.py can say `mobotROBOTICS` without importing anything, because the robotputs that name into main.py's world while it is switching on. Your OWN files donot get that gift. If this file just said `mobotROBOTICS.irs` it would failwith:
NameError: name 'mobotROBOTICS' isn't defined
So every file you write yourself has to ask for the robot by name, once, at thetop - and that is what the line below does. It is not a copy of the robot; itis the very same one main.py is using."""
from startup import mobotROBOTICSimport settings
# What the five eyes are called, left to right, for printing.NAMES = ("far left", "left", "middle", "right", "far right")
def look(): """Read all five eyes.
Returns a list of five True/False values, left to right. True means "this eye can see the black line". """ raw = mobotROBOTICS.irs.readAllIRs() return [value == settings.LINE_READS for value in raw]
def steer(seen): """Turn what the eyes saw into ONE number.
-2 the line is far off to the left +2 far off to the right -1 slightly left +1 slightly right 0 straight ahead, well done None no eye can see the line at all - we are lost """ if seen[2]: return 0 if seen[1]: return -1 if seen[3]: return 1 if seen[0]: return -2 if seen[4]: return 2 return None
def describe(seen): """A human-readable version, for the serial monitor.""" lit = [NAMES[i] for i in range(5) if seen[i]] if not lit: return "nothing" return " + ".join(lit)# wheels.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""wheels.py - the six things this robot's wheels can do.
Same rule as eyes.py: this file has to ask for the robot by name."""
from startup import mobotROBOTICSimport settings
FORWARD = 1 # the Smart Car's motors call forward 1 (both boards, measured)BACKWARD = 0
def _both(left_way, left_speed, right_way, right_speed): mobotROBOTICS.left_motor.setDirectionAndSpeed(left_way, left_speed) mobotROBOTICS.right_motor.setDirectionAndSpeed(right_way, right_speed)
def straight(): _both(FORWARD, settings.SPEED, FORWARD, settings.SPEED)
def nudge_left(): """Slow the left wheel down so the robot leans left.""" _both(FORWARD, settings.SPEED // 3, FORWARD, settings.TURN_SPEED)
def nudge_right(): _both(FORWARD, settings.TURN_SPEED, FORWARD, settings.SPEED // 3)
def spin_left(): """Turn on the spot: left wheel backwards, right wheel forwards.""" _both(BACKWARD, settings.HARD_TURN_SPEED, FORWARD, settings.HARD_TURN_SPEED)
def spin_right(): _both(FORWARD, settings.HARD_TURN_SPEED, BACKWARD, settings.HARD_TURN_SPEED)
def halt(): """Stop. Speed zero, because the Smart Car's motors have no stop().""" mobotROBOTICS.left_motor.setSpeed(0) mobotROBOTICS.right_motor.setSpeed(0)# settings.py — Line follower (Python, four files) (robotics)## A reading copy of one file inside 07-line-follower.mobot.# Editing this copy changes nothing: open the project and edit it there.# main.py imports this file; save it to the board too.
"""settings.py - every number you might want to change, in one place.
Nothing in here does anything. It is just a list of choices, so that when therobot cuts the corners too fast you know exactly which line to edit, and you donot have to hunt through the program looking for a 40."""
# How fast, from 0 to 100.SPEED = 40 # going straightTURN_SPEED = 45 # a small correctionHARD_TURN_SPEED = 55 # the line is right at the edge - lean on it
# What one eye reads when it is over the BLACK line.# If your robot follows the white floor instead of the black tape, change this# to 0 and try again. Different IR boards are wired the opposite way round.LINE_READS = 1
# When every eye has lost the line, spin and hunt for it for this long,# then give up and stop.LOST_SECONDS = 1.5
# How long to rest between decisions. Smaller = twitchier.LOOP_DELAY = 0.02Try changing it
Section titled “Try changing it”SPEED = 55and see where it starts cutting corners.- Make
LOST_SECONDSbig and watch it hunt for ages before giving up. - Add a
sound.pyfile of your own with acelebrate()function, and call it frommain.pywhen the robot has followed the line for 30 seconds.