The PiicoDev magnetometer measures invisible magnetic fields that surround us. I'm going to show you how to get started using it with a Raspberry Pi. We'll connect the two together and get some example code working so that we can use it, just like a magnetic compass. We'll also be able to detect whether there's a magnet nearby. At the end of the tutorial, we'll do a mini project using some other PiicoDev hardware.
To follow along, you'll need a PiicoDev magnetometer and adapter for Raspberry Pi, a Raspberry Pi Single-Board Computer (I'm using a Raspberry Pi 4 today), and a PiicoDev cable. I'm using a longer PiicoDev cable today so that I can keep my magnetometer farther away from my Raspberry Pi. If you want to do some experiments, it's helpful to have a magnetic compass and maybe some magnets as well. Just try not to touch the magnets to the sensor; we don't want to magnetize the sensor itself, just play with the magnetic field around the magnets.
First, plug your PiicoDev adapter onto the headers of your Raspberry Pi. On a Raspberry Pi 4, the Ethernet label will have an arrow that points towards the Ethernet connector. Connect your PiicoDev cable to one of the PiicoDev sockets on the adapter, and connect the other end to your magnetometer. I've powered up my Pi and connected it to the internet. If you need help with that, there is a Raspberry Pi for Beginners workshop.
Once your Pi is powered on, go to the Start menu, Preferences, and Raspberry Pi Configuration. Under the Interfaces tab, make sure that we have I2C enabled. Open the Start menu again, go to the Programming menu, and open Thonny IDE. We'll first make sure that PiicoDev is installed. Under the Tools menu, select Manage Packages, and search for PiicoDev with two I's. Here it is. Just click the Upgrade button to install it.
We can start by downloading the Compass.py script from the article for this tutorial. Right click and select "Save Link As" and save it to a PiicoDev directory in our home directory.
Next, open the script in Thonny. We start by importing the device driver for the magnetometer, and we also import a sleep function. We initialize the device and call it Compass. We set the range to 800 micro tesla. Magnetic field strength is measured in tesla, and this is the 800 micro tesla range for this device. We then call the Calibrate function to calibrate the sensor.
In the infinite loop, we call readHeading and store that in a variable called Heading. If we got some valid data, we then print that heading to the shell. Click the green Run Current Script button and in the shell, we will see that we are now calibrating the sensor. Rotate the sensor on a flat surface very slowly and complete at least one full revolution. There's a progress bar in the shell that's showing our progress and any time a calibration event occurs that progress will reset.
Once the calibration is complete, we will have a printout of the heading in degrees in the shell and we can see that in the plotter as well.
Let's see if we can find magnetic north. I've taped down this paper so it can't move and I've brought out my magnetic compass so we can compare what this compass reads versus our magnetometer. If I scribe a line along this compass and that means that north is in this direction or at least magnetic north. I'll move that away because that needle is magnetic and it could interfere with the magnetometer.
We're measuring the heading that the top of the board points so if I align the side edge with the arrow we should get... look at that we have zero degrees. How good! So that means that the magnetometer agrees with the magnetic compass. That's a good start.
If I turn this 90-degrees to the right we're now facing 90-degrees right which is east and you can see the shell is now printing 90-degrees. Likewise if I rotate it now so we should be facing 180-degrees which is south and 270-degrees which is west.
Now I've got a compass app on my phone and if I line that up with my arrow we can see that it's showing about 10-degrees which doesn't agree with either the magnetometer or the magnetic compass. What's going on here? A lot of applications will default to showing the true heading so magnetic north isn't actually true north. Depending on your location on the earth's surface there could be a difference between magnetic north and true north. If I line my phone up with my magnetic north arrow and then switch the mode to magnetic north we can see that it basically agrees with the compass. So magnetic north is in this direction and true north is really about this direction. So here's my magnetic north line and here's my true north.
Compass calibration is an important step when using a compass. To calibrate, we need to find the magnetic declination of the area we are in. For example, in Newcastle Australia, the declination is about 12-degrees. We can use the online tool to find this information and then use the compass.setdeclination line to set the declination.
When we rerun the script, if we line up the compass with true north, we should be at zero degrees. If we go back to the magnetic north line, we should be at about 12 or 13-degrees.
A file called calibration.cal will appear in the working directory. This file contains the calibration data, so we don't need to call the calibrate line every time we run the script. We can periodically recalibrate the compass if the heading is no longer accurate or if it has been magnetized by a strong magnet.
Let's move on to example 2, detecting a magnet. We can open the detect magnet example and see that the initialization is similar, except this time we are initializing with a range of 3000 microtesla. There is also a threshold set to 80 microtesla.
I'll change that to about 120 for now. And then in the infinite loop we just call read magnitude and that will read the strength of the magnetic field. We save that in a variable called strength and then we print the strength. And if the strength is above some threshold we also say there's a strong magnet. I've got my strong magnet here and I've run the script and we can see that we're getting about 85 microtesla and if I bring that magnet closer we should get it to trigger a strong magnet. There we go. Great so we can detect the presence or lack of presence of a magnet.
I'm going to comment out this if statement and the print statement and change the sleep to 100 milliseconds. The reason for that is I want to look at this graph here, this plot of magnetic field strength. So you can see as I bring that magnet closer and farther away that line moves an awful lot and it's quite exact. You know I'm only moving this magnet a couple of centimetres back and forth and we can really see that in the plot. That's really cool.
Returning to the article, download the raw data example, example three. So again we'll just save that link as and open it in Thonny. This script allows you to read the raw values of each of the three axes in microtesla. So we initialize very similar to every other example and we just call the read function which by default reads in microtesla. If we run that script we can see some numbers printing out in the terminal but more interestingly are these plots. So I have my magnet on the desk facing in this direction which means that there are lines of magnetic field flux going in this direction. So we can see x is blue and y is yellow. If I turn that sensor on the table we can see both x and y reacting quite a lot but the z axis doesn't really react all that much and that's because the z axis is going through the table.
In this direction, there is no magnetic flux lines going. However, if we stand the magnet up on its side, the z axis shoots up. This is because the magnet now has magnetic flux lines going through the table through that z axis. To access the raw data off the sensor, we can use the same function but with the raw equals true argument. This will read the raw data from the sensor adjusted by whatever calibration offsets we have measured.
For a mini project, we have mounted a PiicoDev OLED module onto a small platform with the magnetometer so that as we move the platform, they move together. We have opened up the graphical compass example and the code is really similar to the very first compass example that we ran. This code has a draw compass function which takes in the heading in degrees and it will draw an arrow on the screen to work like a compass needle. On the display, we have a compass needle with a little ball on the end to indicate the direction that it is pointing. As we rotate the whole project, the angle of that needle changes to point in the same direction that our magnetic compass was pointing in the first example.
Using the PiicoDev magnetometer, we can draw a compass needle on the screen. To do this, we need to convert the angle and length of the needle into xy coordinates. The start of the needle is drawn at the center of the screen, and the end is calculated using polar to cartesian coordinates, offset by the middle of the display width over two and height over two. We then draw a line from the center of the display to the calculated coordinates, and draw a circle at those coordinates.
If you make something cool from these starter projects or have any questions, let us know in the comments for this article. We're full-time makers and happy to help. Until next time, thanks for watching.
Makers love reviews as much as you do, please follow this link to review the products you have purchased.