Let's get started with the PiicoDev® Magnetometer. In this guide, we'll connect the Magnetometer to our micro:bit, get it working as a compass, and read the magnetic field strength of a nearby magnet.
To follow along, it's best to have:
- A MicroBit V2
- A PiicoDev Magnetometer QMC6310
- A PiicoDev Adapter for MicroBit
- A PiicoDev Cable - longer cables are useful to keep your Magnetometer away from magnetic interference.
- (Optional) A magnetic compass - to compare measured headings.
- (Optional) A PiicoDev platform helps secure everything together.
- (Optional) A magnet
Contents
- Introduction
- Connect the Magnetometer to your MicroBit
- Download MicroPython Modules
- Example 1 - Compass and Calibration
- Example 2 - Detect a Magnet
- Example 3 - Raw Data
- Conclusion
- Resources
Introduction
A magnetometer measures the strength and direction of a magnetic field. They can be used to detect nearby magnets and even measure the Earth's magnetic field. The PiicoDev Magnetometer measures magnetic field strength in three separate axes (labelled on the board: x,y,z). The direction of these axes shows the positive direction - this means that if the arrow is aligned with a magnetic field in the same direction, the value measured on that axis will be positive.
Connect the Magnetometer to your MicroBit
Plug your micro:bit into the Adapter - make sure the buttons are facing up, as shown in the picture below. Connect your magnetometer to the Adapter via the PiicoDev cable, and finally connect your micro:bit to your computer with a USB lead.
If you're unfamiliar with connecting PiicoDev modules, read the PiicoDev Connection Guide before proceeding.
Download MicroPython modules
We will need three files to easily read data from the Magnetometer:
- Download the PiicoDev Unified Library: PiicoDev_Unified.py (right-click, "save link as").
- Download the device module: PiicoDev_QMC6310.py (right-click, "save link as")
- Download the example script: compass.py (right-click, "save link as" and save as "main.py")
It will be best to keep these files wherever you like to keep your coding projects eg. Documents > PiicoDev
Example 1 - Compass and Calibration
We'll be working in Thonny - if you're unfamiliar working with Thonny see our guide for getting started with Thonny and MicroBit.
Open Thonny, connect to your micro:bit and navigate to where you stored the files from the last step. Right-click each file and select "Upload to /" to upload them to your micro:bit (Hint: View the files menu with View > Files)
Open main.py and run the script (click the Green Play Button, or Ctrl+R). You will be prompted to calibrate the magnetometer: Slowly rotate the sensor on a flat surface until calibration is complete. You can see the calibration progress shown by a progress bar in the shell.
Follow along with the video for this part - getting a high-quality calibration is important for reading an accurate heading.
Once calibration is complete, your micro:bit will begin printing the measured heading into the shell. This is the same heading that you would read off a magnetic compass. The heading is the direction the top edge (with the PiicoDev label) of the module is pointing when placed on a level surface like a table.
If you have a magnetic compass you can compare headings. In the video I scribe a line pointing north - as read from my magnetic compass. I then compare the data gathered by the magnetometer and the results are really close!
You may notice a new file named calibration.cal has appeared on your micro:bit - this is the calibration data. This calibration data will be automatically loaded every time the script runs, so you can comment-out compass.calibrate() if you don't want to calibrate on every power-up. It's still a good idea to calibrate periodically, or if you notice your heading has drifted.
Remix - True North
So far we have been working with Magnetic North - this is the direction a magnetic compass will point. To find a true heading, we need to input some more information. Magnetic Declination is the difference between Magnetic North and True North (or "Geographic North"). The value for declination changes depending on location. In Newcastle, Australia, the declination is about 12° (as of 2022). There are lots of online tools that will help you find the declination in your area (here's one example). Once you know the declination in your area, you can input that angle into the setDeclination() function. Re-run your script and you should notice the heading data has been offset slightly. Your magnetometer is now indicating its measurement for True North.
Example 2 - Detect a Magnet
In this example, we'll measure magnetic-field-strength. This is useful to detect the presence of a nearby magnet. Replace the code in main.py with the following code.
# Read the magnetic field strength and determine if a magnet is nearby from PiicoDev_QMC6310 import PiicoDev_QMC6310 from PiicoDev_Unified import sleep_ms magSensor = PiicoDev_QMC6310(range=3000) # initialise the magnetometer threshold = 120 # microTesla or 'uT'. while True: strength = magSensor.readMagnitude() # Reads the magnetic-field strength in microTesla (uT) myString = str(strength) + ' uT' # create a string with the field-strength and the unit print(myString) # Print the field strength if strength > threshold: # Check if the magnetic field is strong print('Strong Magnet!') sleep_ms(1000)
When we run the script, we see the measured field strength being printed to the shell. If the measured strength goes above a set threshold, the program prints a message to the shell. This time around, the magnetometer is initialised with the maximum range (3000 uT), since there could be a strong magnet nearby. When we exceed the range of the magnetometer, the measurement becomes invalid and so the measurement data is returned as a special "Not a Number" type.
A note about calibration: In Example 1 we performed a 2-axis calibration (rotating the magnetometer on a flat surface. For best results in this example a 3-axis calibration is necessary. To calibrate 3-axes, call the calibrate() function, and rotate the device slowly in all axes.
Above: Bring a magnet nearby the Magnetometer and observe how small movements can be easily observed by the magnetic field strength. The above figure is using modified code that removes other print() statements. Refer to tutorial video to reproduce this example.
Example 3 - Raw Data
The read() method allows you to extract the 3-axis magnetometer data (in uT, or just the raw register data) - for when you wish to process the data with your own algorithm.
# Prints the raw axis readings in micro-Tesla from PiicoDev_QMC6310 import PiicoDev_QMC6310 from PiicoDev_Unified import sleep_ms magSensor = PiicoDev_QMC6310() # Initialise the sensor (defaults to range=3000uT) magSensor.setRange(1200) while True: raw_data = magSensor.read() # Read the field strength on each axis in uT # raw_data = magSensor.read(raw=True) # Read the raw, unscaled data on each axis print(raw_data) # Print the data sleep_ms(200)
Conclusion
We can measure the properties of magnetic fields using a 3-axis magnetometer. Built-in functions allow us to easily measure the sensor's heading in a magnetic field, and we've even been able to use the magnetometer like a compass.
If you make something cool with this starter project we'd love for you to share it on our forums! And if you'd like some help with this guide, start the conversation below - We're full-time makers and here to help!
Resources
Magnetometer Library: PiicoDev Unified MicroPython module for QMC6310
Hardware Repository for the PiicoDev Magnetometer
OLED Library: PiicoDev Unified MicroPython module for SSD1306