Find north — Smart Car (Python)
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 has a compass, and there is no block for it. This example is the clearest reason to graduate from blocks to Python: a whole sensor that only typed code can reach.
Three parts:
- Calibrate — you spin the robot by hand for five seconds and it learns the magnetic field where you are. Once per robot, ever.
- Read — turn the robot by hand and watch the heading; LED 1 lights up when it points north.
- Turn itself — the robot drives its own motors until it faces north.
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: 03-find-north.firmware-3.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A Smart Car (the compass is on the same I²C wires as the colour sensor: SDA 21, SCL 22).
- A USB cable and the serial monitor.
- A bit of floor for part 3, and no big lump of metal on the table — a laptop or a steel table leg will bend the field and the compass will lie.
How to run it
Section titled “How to run it”- Open 03-find-north.firmware-3.mobot and press Run.
- When it says SPIN THE ROBOT SLOWLY BY HAND, do exactly that — pick it up and turn it round and round, once or twice, for five seconds.
- Turn the robot by hand and watch the heading numbers.
- When it asks, put it on the floor and stand back.
What you should see and hear
Section titled “What you should see and hear”- During calibration: LED 1 stays on for five seconds, then
Saved. You will not have to do that again. - Then a heading every half-second: 0 when the robot points north, 90 east, 180 south, 270 west. Turn the robot a quarter-turn and the number should move by about 90.
- LED 1 comes on whenever it is within 12° of north, and goes out when you turn away. That is the part you can check without reading a single number.
- In part 3 the robot spins on the spot and stops facing north, then plays
the little three-note
successtune.
If the numbers jump around wildly, something magnetic is too close, or the spin in part 1 was too fast or did not go all the way round. Delete the calibration and try again (see below).
The trap this example exists to show
Section titled “The trap this example exists to show”compass.heading() on a robot that has never been calibrated does not
return a wrong number. It raises:
RuntimeError: Compass not calibrated. Please run calibrate() method.Every brand-new robot is in that state, and the calibration lives in a file
called compass_cal.json on the robot itself. Updating the firmware with MoBot
Flash erases it: MoBot Flash erases the robot’s whole flash memory before it
writes the new firmware, and the file goes with it. Flashing from the IDE does not
erase the whole memory, so it should leave the file alone, but nothing promises
that for every version. A robot that used to work and starts refusing again after
an update just needs part 1 run once more.
The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Find north (Python) (robotics)## A reading copy of one file inside 03-find-north.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 03-find-north.main.py.
"""Find north - MoBot Smart Car.
The robot has a compass, and NO block can use it. This is a Python-only toy.
Part 1 teaches the compass where it is: you spin the robot slowly by hand forabout five seconds while it watches the magnetic field, and it saves what itlearned into a file called compass_cal.json. You only ever have to do this onceper robot - after that the file is still there when it switches on again.
Part 2 reads the heading over and over, and lights LED 1 when the robot ispointing north.
Part 3 asks the robot to turn ITSELF to face north, using its own motors."""
import timefrom indicators import SONGS
NORTH = 0 # degrees. 90 is east, 180 south, 270 west.CLOSE_ENOUGH = 12 # how many degrees still counts as "north"
compass = robot.compass
if compass is None: print("This board has no compass. (The Mini does not have one either.)") raise SystemExit
# ---------------------------------------------------------------- part 1 ----# Calibrating: the compass needs to see the magnetic field from every angle.## If you never do this, compass.heading() does not return a wrong answer - it# refuses, with RuntimeError("Compass not calibrated..."). A brand new robot# has never been calibrated, so this is where every compass program starts.
if compass.is_calibrated(): print("Already calibrated - skipping straight to the reading.")else: print("SPIN THE ROBOT SLOWLY BY HAND, round and round, for 5 seconds.") print("Starting in 3...") time.sleep(3) robot.led1.on() compass.calibrate() # about 5 seconds, and it saves the result robot.led1.off() print("Saved. You will not have to do that again.")
# ---------------------------------------------------------------- part 2 ----# Reading the heading. 0 is north, 90 east, 180 south, 270 west.
print("")print("Turn the robot by hand and watch the number. LED 1 lights up at north.")
for _ in range(60): # about 30 seconds heading = compass.heading() # heading_error wraps the difference into -180..+180, so 359 and 1 are close. off_by = compass.heading_error(NORTH, heading) facing_north = abs(off_by) <= CLOSE_ENOUGH print("heading", int(heading), "deg off north by", int(off_by)) robot.led1.set(facing_north) time.sleep(0.5)
robot.led1.off()
# ---------------------------------------------------------------- part 3 ----# Now let the robot turn itself. Put it on the floor first!
print("")print("Put the robot on the floor. It will turn to face north in 3 seconds.")time.sleep(3)
# turn_to drives the robot's own two motors until it faces the heading, or# gives up after timeout_s seconds.compass.turn_to(NORTH, speed=30, tolerance=CLOSE_ENOUGH, timeout_s=8)
print("Done. It says it is now facing", int(compass.heading()), "degrees.")robot.buzzer.play_song(SONGS["success"])Try changing it
Section titled “Try changing it”- Change
NORTH = 0toNORTH = 90and part 3 turns the robot east instead. - Make
CLOSE_ENOUGHsmaller (say4) and part 3 takes longer and is fussier. - To force a re-calibration, run this once in the serial monitor:
import os; os.remove("compass_cal.json"), then reset the robot.
The robot has a compass, and there is no block for it. This example is the clearest reason to graduate from blocks to Python: a whole sensor that only typed code can reach.
Three parts:
- Calibrate — you spin the robot by hand for five seconds and it learns the magnetic field where you are. Once per robot, ever.
- Read — turn the robot by hand and watch the heading; LED 1 lights up when it points north.
- Turn itself — the robot drives its own motors until it faces north.
Project for firmware 2.x: 03-find-north.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A Smart Car (the compass is on the same I²C wires as the colour sensor: SDA 21, SCL 22).
- A USB cable and the serial monitor.
- A bit of floor for part 3, and no big lump of metal on the table — a laptop or a steel table leg will bend the field and the compass will lie.
How to run it
Section titled “How to run it”- Open 03-find-north.mobot and press Run.
- When it says SPIN THE ROBOT SLOWLY BY HAND, do exactly that — pick it up and turn it round and round, once or twice, for five seconds.
- Turn the robot by hand and watch the heading numbers.
- When it asks, put it on the floor and stand back.
What you should see and hear
Section titled “What you should see and hear”- During calibration: LED 1 stays on for five seconds, then
Saved. You will not have to do that again. - Then a heading every half-second: 0 when the robot points north, 90 east, 180 south, 270 west. Turn the robot a quarter-turn and the number should move by about 90.
- LED 1 comes on whenever it is within 12° of north, and goes out when you turn away. That is the part you can check without reading a single number.
- In part 3 the robot spins on the spot and stops facing north, then plays a little three-note “success” tune.
If the numbers jump around wildly, something magnetic is too close, or the spin in part 1 was too fast or did not go all the way round. Delete the calibration and try again (see below).
The trap this example exists to show
Section titled “The trap this example exists to show”compass.read() on a robot that has never been calibrated does not return a
wrong number. It raises:
RuntimeError: Compass not calibrated. Please run calibrate() method.Every brand-new robot is in that state, and the calibration lives in a file
called compass_cal.json on the robot itself. Updating the firmware with MoBot
Flash erases it: MoBot Flash erases the robot’s whole flash memory before it
writes the new firmware, and the file goes with it. Flashing from the IDE does not
erase the whole memory, so it should leave the file alone, but nothing promises
that for every version. A robot that used to work and starts refusing again after
an update just needs part 1 run once more.
The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Find north (Python) (robotics)## A reading copy of one file inside 03-find-north.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.
"""Find north - MoBot Smart Car.
The robot has a compass, and NO block can use it. This is a Python-only toy.
Part 1 teaches the compass where it is: you spin the robot slowly by hand forabout five seconds while it watches the magnetic field, and it saves what itlearned into a file called compass_cal.json. You only ever have to do this onceper robot - after that the file is still there when it switches on again.
Part 2 reads the heading over and over, and lights LED 1 when the robot ispointing north.
Part 3 asks the robot to turn ITSELF to face north, using its own motors."""
import time
NORTH = 0 # degrees. 90 is east, 180 south, 270 west.CLOSE_ENOUGH = 12 # how many degrees still counts as "north"
compass = mobotROBOTICS.compass
if compass is None: print("This board has no compass. (The Mini does not have one either.)") raise SystemExit
# ---------------------------------------------------------------- part 1 ----# Calibrating: the compass needs to see the magnetic field from every angle.## If you never do this, compass.read() does not return a wrong answer - it# refuses, with RuntimeError("Compass not calibrated"). A brand new robot has# never been calibrated, so this is where every compass program has to start.
if compass.is_calibrated(): print("Already calibrated - skipping straight to the reading.")else: print("SPIN THE ROBOT SLOWLY BY HAND, round and round, for 5 seconds.") print("Starting in 3...") time.sleep(3) mobotROBOTICS.led1.on() compass.calibrate() # about 5 seconds, and it saves the result mobotROBOTICS.led1.off() print("Saved. You will not have to do that again.")
# ---------------------------------------------------------------- part 2 ----# Reading the heading. 0 is north, 90 east, 180 south, 270 west.
print("")print("Turn the robot by hand and watch the number. LED 1 lights up at north.")
for _ in range(60): # about 30 seconds heading = compass.read() # angle_error wraps the difference into -180..+180, so 359 and 1 are close. off_by = compass.angle_error(NORTH, heading) facing_north = abs(off_by) <= CLOSE_ENOUGH print("heading", int(heading), "deg off north by", int(off_by)) mobotROBOTICS.led1.setState(1 if facing_north else 0) time.sleep(0.5)
mobotROBOTICS.led1.off()
# ---------------------------------------------------------------- part 3 ----# Now let the robot turn itself. Put it on the floor first!
print("")print("Put the robot on the floor. It will turn to face north in 3 seconds.")time.sleep(3)
# turn_to_heading drives the motors, so you have to hand it the motors.# It will not go and find them by itself, and it is easy to forget.compass.turn_to_heading( NORTH, base_speed=30, tol_deg=CLOSE_ENOUGH, timeout_s=8, L=mobotROBOTICS.left_motor, R=mobotROBOTICS.right_motor,)
print("Done. It says it is now facing", int(compass.read()), "degrees.")mobotROBOTICS.buzzer.play("0 C5 1 0;1 E5 1 0;2 G5 2 0", looping=False)Try changing it
Section titled “Try changing it”- Change
NORTH = 0toNORTH = 90and part 3 turns the robot east instead. - Make
CLOSE_ENOUGHsmaller (say4) and part 3 takes longer and is fussier. - To force a re-calibration, run this once in the serial monitor:
import os; os.remove("compass_cal.json"), then reset the robot.