How to Calibrate a Magnetometer | Digi-Key Electronics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
if you've ever worked with a magnetometer you might realize how much of a pain it is to get these things to work as a digital compass if i compare it to my phone here you can see i'm lining it up and my direction of heading should be this way and it doesn't seem to matter kind of how much i turn i can't get that 153 oh wait here we go 153 is not even here that's because this magnetometer has not been calibrated and we're also not applying magnetic declination to convert magnetic north to true north or a magnetic heading to our geographic heading i'm going to show you how to calibrate your magnetometer as well as apply magnetic declination so that we can get a magnetometer working as a much better digital compass let's get started [Music] the two main settings we care about are hard iron calibration and soft iron calibration i'll go through both of these in this video so that you can get a better understanding of how to use your sensor and get relevant or useful data out of it the other thing we care about is magnetic declination this is the value we get from a compass or digital compass that helps us get our heading as related to the magnetic north and south poles of our planet if you want to convert that information into a geographic heading as determined by the geographic north and south poles we have to do a little bit of math to make that conversion let's say that we have a magnet that exerts some force on other magnetic material or ferrous material for our purposes we'll assume the earth acts like a basic bar magnet we can visualize this force as a vector field the strength and direction of the force at any point depends on how far away from the magnet you are and your relative position to the magnet or the poles of the magnet we can use a magnetometer to measure the strength of this field a 3-axis magnetometer like the one i'm using gives us the strength of each of the x y and z components from that we can determine the direction and strength of the field at any point in space if we keep our sensor parallel to the ground meaning the z-axis points directly up into space or toward the center of the earth we can calculate the heading by taking the inverse of the tangent of x over y this has the y axis pointing toward our heading you can flip x and y if you want to have x pointing toward the heading note that most heading values are given in degrees so you'll likely need to convert from radians to degrees you might need to multiply the result by negative one depending on if your z-axis is facing toward the sky or toward the ground with y as our heading and z pointing toward the sky we'll want that negative one i have my system displaying the raw x y and z magnetic field values in microtesla hard iron distortion occurs when there are permanent magnets in the area keep in mind that these could be in nearby speakers and motors this causes a simple additional bias to the x y and z values which you can see occurring on the screen here to correct for this we measure this bias and subtract those values from our raw readings soft iron distortions occur due to the presence of objects that bend or warp the existing magnetic fields ferrous materials like iron and steel is notorious for introducing soft iron distortions we have to do some complex math to compensate for soft iron distortions but luckily we have some tools to help us out electronics contain a bunch of ever-changing currents which produce magnetic fields these can be nearly impossible to accurately model and it's not something i'll get into here to make it easy i recommend performing hard and soft iron calibration with your magnetometer once you have it enclosed and mounted this includes having any nearby electronics running that you might use to start the calibration process we're going to need to collect raw magnetometer data from a sensor in this case i'm going to use an adafruit breakout board that contains an lis 3 mdl magnetometer and that has three axes as you can see given by the graphic here we don't need an oled for this so i'm just going to remove this component and i'm going to connect it to an arduino board over i squared c i'm using quick or stemma for this so feel free to make your connections note that i'm using the adafruit libraries for this and their sensorlab libraries don't work very well with something like an arduino uno or anything based on the 328p or 32u4 so you need to use something a little more powerful this is mainly due to the fact that it requires a lot of flash space so i'm going to be using a sam d21 chip and this is a feather m0 logger but you don't really need that this is just the board i had available go ahead and connect everything up plug this into your computer and let's head over to arduino you're welcome to use any language you like on many boards you'd like the main thing is we need to get raw data generally in microtesla captured from the magnetometer and sent over to another computer program that will perform the calibration process for us i'm going to use arduino because it's easiest and adafruit has a number of nice libraries to help us out to use this board you'll want to go to your board manager urls under file preferences and make sure you add the adafruit.github board index to the list of board manager urls once you've done that go to your board manager search for adafruit samd boards and you'll want to install the latest version of this for me 1.7.8 is what worked install that and then go to your include library under sketch manage libraries and search for the adafruit sensor lab you'll want to install this i used 0.7.1 and then we want file examples look for the adafruit sensorlab calibration and you want am you cal no save note that this was originally written for imus or nine dots we just care about the magnetometer version of this this will work with that particular magnetometer i just showed you it just won't read your accelerometer or gyroscope because those aren't attached to the board but this will work anyway all it's going to do is connect to the magnetometer it'll try to connect to a gyroscope and accelerometer if they exist otherwise it just ignores those it will get the event and this contains sensor data it's going to convert those to micro tesla and send them out in two different formats in this case raw and unified data i'm going to start the upload process make sure you have your board selected this is the same d21 board com13 that looks good i'm going to upload this motioncal is a computer program from pjrc that will look for data coming out of the serial port in this particular format with this raw header it will take that and then do the calibration for you we just care about the magnetometer information here which i believe is micro tesla times 10 so that you can get a good integer value other programs like the jupiter notebook that i'll show you use this unified format where it just comes out in pure micro tesla format without multiplying by 10. once it's done uploading you can open the serial monitor and you can see this information flying by as you can see the raw format is an integer version that's the micro tesla times 10 the unified is the actual floating point value so that's how these two are related the two programs we'll look at will read these values in their raw format parse them and then use them for calibration notice that our accelerometer and gyroscope data is zero for these cases because the calibration programs we'll use we'll just ignore them for now we don't care about calibrating with them they are useful if you want to fully calibrate and imu for doing things like absolute orientation for something like a vr headset but we don't care about that right now let's close out of this and we'll open up a jupiter notebook this jupiter notebook was originally written by adafruit but i modified it a little bit so that we can see what's going on the original one was used for hard iron calibration we're not going to ultimately use this program for calibration we're going to use that pjrc motion cal because that does soft iron as well as hard iron but this is a very useful demonstration to see what's going on in hard iron distortion so let's skip past these if you don't have matplotlib and pi serial installed you'll want to uncomment this line and install them here are some imports this is a magic command so that we can do animations in jupyter notebook using matplotlib if you're using this you'll want to set up say the port as well as the history size we'll keep interval at 10 milliseconds if the serial port is open we'll close it make sure you've closed out of the serial monitor in arduino and we're going to open it again to that arduino if you see opened the serial port that means it's working this function is to capture some serial data from that imu or the arduino in this case we're going to ignore most of the imu data and just use the magnetometer data notice here we're using the unified format not that raw format when you run this cell immediately start moving your magnetometer at all different orientations pretend it's a model rocket ship or an airplane or something and you're just trying to make it face every possible direction we're collecting raw x y and z data mapping them to a sphere and then projecting that sphere onto three different planes so you can get an idea of what the x y and z coordinates look like when you're done collecting data you can push the stop button up here ideally you'll want these circles filled in but this is going to be good enough for now next we calculate the ranges that give us the x y and z the maximum and minimums for those axes and then the hard iron correction simply takes that range and divides it by two that's all that's really going on is you find that middle point between the minimum and maximum values for each of your x y and z axes with this hard iron offset you can then subtract that value this bias from your raw x y and z readings to get a correction for our hard iron distortions and with that our circles should line up with each other and ideally they should be more or less over zero zero for the center point this gives you the hard iron correction values that you can start using in your program if you've mounted your magnetometer near some type of permanent magnet like say a speaker however this doesn't help us with soft iron corrections with soft iron distortions these circles will start to appear more elliptical in one fashion or another along one particular axis we need to do some complex matrix mathematics in order to find those correction values i won't get into those here but we will use a piece of software to do those corrections for us head to pjrc.com store slash prop underscore shield.html scroll down and you can find the motioncal software to download so download it for your particular operating system i'm on windows i've downloaded it and install it and it looks something like this before we go here though make sure you reset your board or you'll want to run the cell that's up here if you're still connected to your jupyter notebook this will close out that serial port from here we can now go ahead and run the motioncal software and we can connect to our board go to port connect your board and we're going to do this exercise again of moving this magnetometer around in all different positions try to move it in a sphere facing all possible orientations twisting it where you can pointing it towards their different walls the ceiling the ground moving it up and twisting it and we're trying to get that gaps number to be below about one or two percent all right and that's probably good enough so i'm going to say none and we have our hard iron and soft iron calibration results here on the top right these are the numbers you will want to use to plug into your program to do that i'm going to open up this mag calibration test and i will make sure to put a link to all of this code that's going to be in a github repository in the description of this video this actually does the exact same thing we were doing before where it just sends out raw and unified data to whatever programs listening to it but it's going to apply hard iron and soft iron calibration to those results and i'll show you what's going on here in just a second make sure we're not connected i'm going to move that program over so we can see the calibration results the magnetic offset is the hard iron calibration results if you don't want any calibration these should just be zero zero zero as that subtracts zero from all of your raw data but i'm going to plug these in so we have those stored and we need to do soft iron if you don't want any calibration for soft iron it should be the identity matrix with one down your diagonal and zeros everywhere else as you can see it's very close to the identity matrix there's not much in the way of soft iron calibration as there was no real ferrous material near the magnetometer i honestly tried doing this with the file nearby which is quite ferrous however because i couldn't hold it steady at a particular distance away from the magnetometer these readings would be off regardless of where i tried to put the magnetometer i couldn't maintain that distance to make this demo work nicely but this should give us good readings in motion cal as it is if we scroll down you can see that all we're doing is connecting to the magnetometer we're going to print some stuff out to the serial port in our loop we're going to get the raw readings which are stored in this event struct this is just your x y in z it should come in micro tesla we're going to apply these hard iron offsets all that's happening here is we subtract the hard iron x offset from the raw x value and we do that for y and z as well and we're storing it in this hard iron calibration array so 0 1 and 2 is x y and z we're going to use that in our soft iron scaling there's a pretty good paper i found on soft iron calibration it covers heart iron as well but they demonstrate how to use the calibration data to get calibrated values it's fairly straightforward matrix multiplication we have our raw values we subtract the hard iron offsets which we've already done so this term becomes our hard iron corrected values and we're going to do simple matrix multiplication with our soft iron calibration values and these corrected values for hard iron and all we do is multiply this first value by the value here the next value by the next value and we multiply this value by this value we sum those together to get the soft iron corrected value for x we're going to do the same thing for y so we add this term times this term plus this term times this term plus this term times this term and that becomes our y we repeat the process for z as well so this bottom row multiplies by this vector and we get z so that's how we're getting our fully calibrated for hard iron and soft iron values from our magnetometer and that's what this for loop is doing it's just going through and performing that matrix multiplication this mag data stores our corrected values and we're going to print those out let's go ahead and upload this to our arduino and we're going to head back to our calibration tool here once that's done you can minimize out of arduino because what we care about is looking at the values from this tool let's connect to our board and we're going to do that exact same exercise we'll remove this magnetometer around in all different orientations trying to get that gaps down to something below one percent when you're done my gaps are close to one percent or lower which is fine what you should see is that your magnetic offset your hard iron offsets are closer to zero they're a lot better than they were and your soft iron offsets your magnetic mapping these should be very close to the identity matrix where it's one down the diagonal and zeros everywhere else it's really hard to get these to be exactly that but as you can see this is fairly well calibrated at least for my magnetometer in that particular position now if i move it somewhere else there are other magnetic fields going on there are other soft iron effects and these will change this is why it's a good idea to always calibrate once you have your magnetometer mounted in the place you want it and running next to any of the electronics because those will affect some of these values as well from here let's use this information to make a digital compass i have already copied in the hard iron and soft iron calibration this should match what we found earlier from running motion cal it lines up with these values the other thing we care about is magnetic declination if we were to use the hard iron and soft iron so we scroll down here where we calculate the heading and this is the equation i showed you earlier in that slide assuming that y is pointing in the direction of our heading we can convert it to 0 to 360 degrees and this would get you a magnetic heading where zero degrees is pointing towards magnetic north if we head to this really slick page on colorado.edu you can see an animation showing how the earth's magnetic field and poles move over the years that's because the magnetic poles do not line up with the geographic poles the earth spins along the geographic poles that's true north and true south however the magnetic poles don't exactly follow those and in fact they move quite a bit in some areas along these declination lines i believe they're shown in green here magnetic north and south do line up with geographic north and south so you don't need to care much about adding or subtracting that declination value however everywhere else you do need to care if you want to convert from magnetic heading to a true or geographic heading if you want your application to work like a compass would you don't need to worry about this because a compass follows the magnetic fields not the geographic ones or the geographic lines but if you do care about true heading then we do need to do this conversion i recommend going to ngdc.noaa.gov geomag declinations.shtml there's a magnetic declination calculator that you can find here so click calculate you can find your latitude longitude i'm in new orleans so i'm going to type that in it's going to give me the latitude longitude i'm going to click calculate and it gives me my declination value notice here that there's some plus or minus we don't care much about that we're going to go with this one value here also notice that it changes over time so if you're making an application that's going to last more than a year say for example you might want to revisit this site to get new declination values or consider connecting something to the internet and with gps like a cell phone that can automatically update your declination values to your application that's how cell phones are able to do it they have gps and internet built in they can automatically figure out where you are and calculate the magnetic declination values automatically without you having to enter them but for our application we need to do them manually let's bring up a calculator notice here that we have degrees and minutes we want this to be in degrees with decimal degrees we want it to be a floating point value not this minutes stuff so we're going to take 14 we're going to divide it by 60 to get .2333 and we're going to add 1. so this is our magnetic declination value east if there's an e here that's positive west is negative so this is negative 1.2333 if i'm in new orleans let's go back into our application and we're going to scroll up to where it asks for that magnetic declination value we're going to enter minus 1.233 you can keep going with decimals if you'd like but that should be good enough remember that this is not going to be very precise because we're also not accounting for things like tilt on our magnetometer and if i move around even within this city this is going to fluctuate a good bit this value this magnetic declination value is used it is added to our heading once we calculate that in degrees and then we convert it to 0 to 360 degrees by default this is going to give you something like negative 180 to positive 180 and when you talk about headings it's usually 0 to 360. so that's how we do that calculation if it's west this is subtracted from heading if it's east it's added to heading that's all we have to do for magnetic declination right now this sample code is spitting out to an oled so you can see it when i show it to you on the camera i will make sure to update this code for you so that you can enable or disable oled so that it will print right to your serial terminal if you want to try it without needing an oled but for now let's upload this to the board and see if our digital compass works with the calibration data added it's a lot closer to the heading that's given by my phone couple things to note here one is as you move closer to magnetic material ferrous material or other electronics you can see it really starts to throw off these values so try to keep it away from new materials if you add it to new materials or have it close by you're going to need to recalibrate the other thing is we are pointing towards a geographic heading and that's the number being given here which should line up with the geographic heading on my phone as i turn the board side to side it throws off that calculation so be aware of which axis you are using to point towards your heading so i'm using y and then x for my calculation so as x moves away from those field lines it's going to throw off the calculation which you can see here let's rotate my phone a little bit and see if it keeps up so we'll point it directly south and make sure it's level with the ground and sure enough 180 and we'll keep rotating you can see the comp is moving there 173 is about this way and it's not going to necessarily be exact but it's pretty close once again it depends on how parallel i'm keeping this thing to the ground hopefully this gives you a start remember that wherever you install this you will need to re-run your calibration and update the settings in your program i hope this helps you get started with magnetometers and as a result using them as digital compasses we didn't even get into tilt compensation that's where you have an accelerometer on the same border plane as your magnetometer and you use the information from that accelerometer to compensate for the amount of tilt or orientation that your board is in so that you can use the magnetometer to get a heading regardless of that orientation have fun navigating and as always happy hacking [Music] you
Info
Channel: DigiKey
Views: 69,850
Rating: undefined out of 5
Keywords: adafruit, arduino, calibration, compass, computer engineering, digikey, digital compass, electrical, electrical engineering, electronics, electronics engineering, engineer, engineering, hard iron, magnetometer, maker, microcontroller, project, sensor, soft iron
Id: cGI8mrIanpk
Channel Id: undefined
Length: 26min 21sec (1581 seconds)
Published: Mon Jun 20 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.