PiicoDev Magnetometer QMC6310 - Guide for Raspberry Pi Pico

Updated 29 April 2022

Let's get started with the PiicoDev® Magnetometer. In this guide, we'll connect the Magnetometer to our Raspberry Pi Pico, get it working as a compass, and read the magnetic field strength of a nearby magnet. Finally, we'll remix the code to create a graphical compass display.

To follow along, it's best to have:

If you prefer not to use the Expansion Board for Raspberry Pi Pico, there are other connection options in our PiicoDev Connection Guide.

Contents

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 Pico

Plug your Pico into the Expansion Board, connect your magnetometer to the Expansion Board via the PiicoDev cable, and finally connect your Pico to your computer with a USB lead.

If you're unfamiliar with connecting PiicoDev modules, read the PiicoDev Connection Guide before proceeding.

connect-piicodev-magnetometer-to-raspberry-pi-pico

Download MicroPython modules

We will need three files to easily read data from the Magnetometer:

  • Download the PiicoDev Unified LibraryPiicoDev_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 Thonny and Raspberry Pi Pico.

Open Thonny, connect to your Pico 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 Pico (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.

piicodev-magnetometer-qmc6310-calibration

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 Pico 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.

piicodev-magnetometer-qmc6310-heading-example

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!

piicodev-magnetometer-qmc6310-heading-compare


You may notice a new file named calibration.cal has appeared on your Pico - 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
# magSensor.calibrate()

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.

piicodev-magnetometer-qmc6310-field-strength

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)

Project - Graphical Compass

So far we've been using the shell to visualise information collected from the magnetometer. Now for a fun mini-project. We can use a PiicoDev OLED Module to display a digital compass-needle that always points north. The following code is really similar to Example 1, except there's extra code to drive the display, and handle drawing an indicator on the display.

To follow along with this project, you'll need to save PiicoDev_SSD1306.py onto your Pico.

# Similar to the compass example, this demo uses a PiicoDev OLED module to show a compass graphic

from PiicoDev_QMC6310 import PiicoDev_QMC6310
from PiicoDev_SSD1306 import create_PiicoDev_SSD1306, WIDTH, HEIGHT
from PiicoDev_Unified import sleep_ms
from math import sin, cos, radians # for calculating the compass-needle co-ordinates

compass = PiicoDev_QMC6310(range=1200) # Initialise the sensor with the most sensitive range. Valid ranges: 200, 800, 1200, 3000 uT
oled = create_PiicoDev_SSD1306()
# compass.calibrate() # only need to calibrate once

# Declination is the difference between magnetic-north and true-north ("heading") and depends on location
compass.setDeclination(12.5) # Found with: https://www.magnetic-declination.com/Australia/Newcastle/122944.html

centreX = int(WIDTH/2)
centreY = int(HEIGHT/2)

# This function draws the artwork onto the OLED display. It takes a heading and draws a line at that angle from the centre of the display - along with some other nice stuff.
def drawCompass(heading):
    rads = radians(heading + 180) # convert heading to radians and offset by 180 degrees (to account for y increasing down the display)
    length = 25 # compass needle length (in pixels) from centre
    
    # Convert polar coordinates (length, angle) to cartesian coordinates (x,y) for plotting on display. Offset the coordinates by half the screen width/height to draw from the centre - rather than the top-left of the display.
    x = int( length * sin(rads) + WIDTH/2 )
    y = int( length * cos(rads) + HEIGHT/2 )
    
    # Plot the compass on the display
    oled.fill(0)
    oled.line(centreX, centreY, x, y, 1) # draw the compass needle
    oled.circ(x,y,4)                     # put a north-indicator on the end
    oled.text(str(heading),100,57)       # show the heading in the bottom-right corner
    oled.show()

while True:
    heading = compass.readHeading()
    if compass.dataValid(): # only draw for valid data - prevents errors
        heading = round(heading)
        drawCompass(heading)
    print(heading)

    sleep_ms(100)

The drawCompass() method converts the heading into x,y coordinates that draw a line to the centre of the display. A circle is drawn on the end of the line and the heading in degrees is shown in the bottom corner of the display.

piicodev-magnetometer-qmc6310-project-pico

Above: a compass needle is animated on the OLED to point North, even if the whole assembly is rotated.

Conclusion

We can measure the properties of magnetic fields using a 3-axis magnetometer. Build-in functions allow us to easily measure the sensor's heading in a magnetic field, and we've even built a cool graphical compass project using an extra display module.

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

Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.