Saturday, February 7, 2015

Making a Compass (magnetometer) with Arduino (HMC5883l)

Adafruit 2015
I got a couple of these great little magnetometers in the mail the other day. Their model number is HMC5883l. They are three-axis, measuring the strength of magnetic fields in the X, Y, and Z directions.  They also make use of the I2C communication protocol, so hooking one up is a breeze. NOTE: Due to the workings of the I2C protocol, you are limited to only one magnetometer per microprocessor.

I used an Arduino Nano for this, but like most things Arduino, it really doesn't matter which Arduino you use! However, the I2C pins vary from model to model, so here is a table:

BOARD                            I2C Pins
Uno, Ethernet                    A4 (SDA), A5 (SCL)
Mega2560                         20 (SDA), 21 (SCL)
Leonardo                           2 (SDA), 3 (SCL)
Due                                    20 (SDA), 21 (SCL), SDA1, SCL1
Nano                                  A4 (SDA), A5 (SCL)
Pro Mini                            A4 (SDA), A5 (SCL)


The initial setup
Like most projects, there is no use reinventing the wheel. I found that Adafruit actually has taken a here. You'll need to add the Adafruit Sensor library (here) and the Adafruit HMC5883 library (here) in order to simplify your life immensely. Adafruit have gone and not only converted all values to microgauss, but they've also done the math and calculated the heading! NOTE: For more on the math, see this write-up by Honeywell (here).
LOT of the hardship out of this sensor, and have a pretty great wiring guide

Adafruit 2015

Alright, so we're spitting out something that looks like this:

Adafruit 2015

Now what!? Why direction of course! I've broken the compass down into regions, and then wrote a bunch of if/then statements to print the compass headings.

Here is the code:


So there you have it, a working compass. Be sure to keep it level and it will work just fine!



No comments:

Post a Comment