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!

Transcript

Today I'm going to show you how to get started with your PiicoDev magnetometer and a Raspberry Pi Pico. We'll connect these two together and get some example code working to use the magnetometer just like we would a compass so we'll be able to read like a magnetic heading. We'll also be able to detect the presence of a nearby magnet and at the end of the tutorial we'll even do a mini project with a display to make like a graphical compass.

To follow along you'll of course need a Raspberry Pi Pico with the pin soldered facing downwards, a PiicoDev expansion board for Raspberry Pi Pico and a magnetometer. I'm using a pretty long PiicoDev cable here just so I can keep my magnetometer away from anything metal. They're quite sensitive and if there's something metal nearby that can disrupt the readings.

First plug your Pico into the expansion board with the USB socket at the same end as the two pin battery connector. Connect your PiicoDev cable into the socket at the bottom and connect the other end to your magnetometer. Next connect to your computer with a USB cable. In the article for this tutorial find the download section and right click each link and select save link as. I'm going to save these to a PiicoDev directory in my documents. Instead of saving this last file as compass.py I'll save it as main.py.

We're going to be using Thonny to program our Pico today. If you haven't done that before check out our guide for getting started. Open up Thonny, connect to your Pico and navigate to where you saved those three files we just downloaded. Click the first, hold down shift and click the last, then right click and upload to your Pico.

If we open up the main file stored on the Pico we can see that this is a compass example. We start by importing the magnetometer module and we also import a sleep function. We initialize the magnetometer and then we enter a while loop.

The magnetometer is being initialized with a range of 800 micro tesla. Magnetic field strength is measured in tesla in the SI units. We are going to calibrate the compass and then take a heading and print it. After running the script with ctrl d, calibration instructions will appear. To calibrate, the magnetometer must be kept flat against the table and rotated slowly and steadily for at least one full revolution. As the progress bar fills up, any events that need to be logged will reset the progress bar.

Once the compass is calibrated, a heading will be printed out into the shell. This heading is as if the device were a compass, so whichever way the top of the board is pointing is where the reading will be taken. To verify that the magnetometer is pointing in the correct direction, a real magnetic compass can be used. North can be found with the compass and a line can be ruled to mark magnetic north. If the magnetometer is aligned with the line, it should be pointing in magnetic north.

By rotating 90-degrees clockwise and holding it to the line, the compass should be facing east and the shell should print 90-degrees. Likewise, if the compass is rotated to a full 180-degrees, it should be facing south and the shell should print 180-degrees. With this, a working magnetic compass is created. It is important to note that a magnetic heading is not true north.

Everywhere on the globe, the magnetic direction of magnetic north is offset a little bit from true north. This is called magnetic declination. Here, if I bring my phone into the picture, I'm running a compass application. You can see I've aligned my phone with the line, but I'm reading about 12-degrees. This is because my phone is looking for true heading. If I select magnetic heading, we're basically facing magnetic north now.

Where I am in Newcastle Australia, there's actually a 12 degree difference between magnetic north and true north. There's actually a setting you can apply to the compass to account for this declination. If I uncomment this line here, we're setting the declination to 12.3 and I found this using an online tool. I'm going to comment out calibrate because I don't need to run that again once I've calibrated. And now when I run the script and align with magnetic north, I get a reading of around 12-degrees. To actually point to true north, I would have to rotate anti-clockwise by about 12-degrees.

After calibrating your magnetometer, you may have noticed an extra file appear on your Raspberry Pi Pico. This is the calibration data that we collected during calibration. This file is read every time you initialize the magnetometer if it's present. If this file isn't present, you'll just get a warning that we're running uncalibrated. By saving this data in this file, it means we don't need to calibrate every time we run our script. You might want to recalibrate if your magnetometer is ever nearby a permanent magnet.

Let's move along to the next example. Return to the article and find example 2 for detecting a magnet. Highlight and copy all of that code and we'll paste it into main.py on our Pico. The setup here is pretty similar. We do the same setup as before, but this time we're going to detect a magnet.

We're importing the same libraries as before and doing the same imports. This time we're setting the range to the maximum range, 3000 microteslas, because we're going to be working with some strong magnets. There's a threshold programmed and this script will just read the magnetic field strength, print that strength, and then decide is the magnetic field strong or not.

If I run the script with ctrl r we can see the magnetic field strength being printed in microteslas. If I bring my magnet closer and closer we'll see that strength go up. Once we cross the threshold we get the message strong magnet.

As a quick remix I'm going to comment out that strong magnet print and we'll make this run every 100 milliseconds so that we can open the plotter and view a graph of magnetic field strength. I'll rerun the script and now as I move that magnet closer and farther away you can see the field of influence of the magnet only begins to pick up about here and if I spin the magnet around that will also change the field strength as well. That's quite interesting.

So you could use a program like this for detecting the presence or lack of presence of a magnet and have your program do something depending on whether there's a magnet nearby. Security systems work like this to detect whether a window or a door is open or closed.

Return to the article for the tutorial and copy the raw data example into your main script. This is just going to read the raw magnetic field strength in each of the x y and z axes. So the numbers printing up the shell are the magnetic field strengths in micro tesla and if we open up the plotter we can have a bit of a play with this magnet. You can see as I move the magnet closer and farther away it makes sense that the axes would change. Here the magnetic field lines are coming out of the magnet and mostly going down through the z-axis. So if I rotate the magnet onto its side

We should be able to affect that blue line a lot. Okay, so now the blue line has fallen pretty close to zero and that's because all the field lines are going around in this axis. There's very, very little magnetic flux going through the z-axis, which is going vertically through the sensor. That also means that if I spin the magnet around, x and y are going to change a lot. The z is decoupled from that because, again, I'm spinning the magnet around this way, there's no magnetic lines going through the z-axis.

You might want to use this raw data if you want to do your own signal processing. And if you really, really want to, you can include the raw argument raw equals true and that will just print rather than units of micro tesla, this will just print the raw register values coming straight out of the sensor.

And now for a fun little project, I've mounted everything onto a PiicoDev platform to keep it nice and stable and I've brought in a PiicoDev oled module which is a small display. This project is very similar to the first compass example we saw, except now I'm drawing a graphical compass needle on the display. So, as I pick this platform up and turn it in place, we can see the needle is always pointing in the north direction and there's even a heading in degrees printed on the screen as well.

If you'd like to recreate this project, you can find the code at the bottom of the article. It's very simple to the first compass example; the major difference is this new function that I've called draw compass. This is basically taking the heading, setting the length of our compass needle, and then converting that angle and length into an x and y coordinate to draw the end of our compass needle from the center. So, our compass needle is drawn as a line from the center of the display and it's drawn to the point x y that we just calculated from the length and angle.

With just a little bit of extra code and an extra module, we can level up what we can do with this magnetometer. If you make something cool from this starter project, or if you have any questions, let us know in a comment at the bottom of this article. We are full-time makers and happy to help. Until next time, catch you later!

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.