Friday, August 30, 2013

Arduino: simple compass with HMC5883L + Library


One of the most popular I2C-compatible magnetometer is the Honeywell HMC5883L. These sensors’ solid-state construction with very low cross-axis sensitivity is designed to measure both the direction and 
the magnitude of Earth’s magnetic fields, from milli-gauss to 8  gauss. 
In this tutorial I'll try to: 
  1. Introduce how a magnetometer works
  2. Explain how to retrieve the heading from the magnetometer data
  3. Provide the little library I wrote for Arduino IDE

How does a magnetometer work?

An electronic magnetometer like the HMC5883L is based on the Anisotropic Magnetoresistance phenomenon. Mastering the physics that descibe the phenomenon is not an easy task, since this is a huge field whose depths we cannot hope to begin to plumb in these few words. 
Basically, the a magnetic field interacts with the path of the current flowing through a ferrous material, according to the Lorentz Law hence the resistance of the material seems to change to the observer. You can imagine as if the bar of ferrous material (e.g InSb) grows longer, raising its electric resistance. Therefore measuring the change in the resistance we can estimate the magnetical field! The Equation that rules the phenomenon is in the image below. For a further investigation of the matter, especially on the electronics a magnetometer is based upon, you could read this.

From the raw data to the north! 

Supercomputer models of Earth's magnetic field from

In a compass, the magnetic field you measure is the earth's one. It is tangential to the surface of the planet and it flows from north to south. The HMC5883L has three different axis to calculate the headings, as you may not know the tilt of your device (i.e. our quadcopter) when you need the data! Anyway for this example we will assume that the sensor is flat on a table, so we don't have to worry about its tilt. Therefore we'll use only X and Y axes data.

We'll assume Hz =0

Hence the angle between the Y axis and the magnetic north will be, according to the quandrant:

Direction (y>0) = 90 - [arctan(x/y)] * 180 / π
Direction (y<0) = 270 - [arctan(x/y)] * 180 / π
Direction (y=0, x<0) = 180.0
Direction (y=0, x>0) = 0.0

First of all we have to scale the raw data according to the scale we chose.
The valid gauss values are: 0.88, 1.3, 1.9, 2.5, 4.0, 4.7, 5.6, 8.1. Of course for a geo-compass we just need 1.3 Ga, that leads us to a 0.92 [mG/LSb] of resolution and a gain of 1090 [LSb/Gauss]. The code I provide with this post is based on the code found here, but at the time this post is written, the original code won't work. There are some huge bugs as floating point number comparison that will not allow you to change the scale factor of the sensor, and some queer bugs on error handling (basically that code doesn't check for error at all, as you can easily prove executing it: it will always display an error setting the scale, and setting the measurement mode. More oddly this latter error display the same message because the error variable is not reset after its use). Of course even my library will have some bugs too, and it's not complete at all, but it's a good start to familiarize with the sensor itself.

Here is the code with a lots of comments:

On the image below you can see how the heading measured with an iPhone 4 is quite close to the one we read from Arduino. There are many margin of improvement. First, we ought compensate the potential tilt of the device using the accelerometer data from the ADXL345, for example using the info on my previous post! Moreover, my breadboard has an aluminium ground plane at its bottom, which can obviously make harder for the structure to sense the magnetic field and/or could drift it and create an offset.


  1. Thank you very much for the good info and library!!!!

    Work from home theory is fast gaining popularity because of the freedom and flexibility that comes with it. Since one is not bound by fixed working hours, they can schedule their work at the time when they feel most productive and convenient to them. Women & Men benefit a lot from this concept of work since they can balance their home and work perfectly. People mostly find that in this situation, their productivity is higher and stress levels lower. Those who like isolation and a tranquil work environment also tend to prefer this way of working. Today, with the kind of communication networks available, millions of people worldwide are considering this option.

    Women & Men who want to be independent but cannot afford to leave their responsibilities at home aside will benefit a lot from this concept of work. It makes it easier to maintain a healthy balance between home and work. The family doesn't get neglected and you can get your work done too. You can thus effectively juggle home responsibilities with your career. Working from home is definitely a viable option but it also needs a lot of hard work and discipline. You have to make a time schedule for yourself and stick to it. There will be a time frame of course for any job you take up and you have to fulfill that project within that time frame.

    There are many things that can be done working from home. A few of them is listed below that will give you a general idea about the benefits of this concept.

    This is the most common and highly preferred job that Women & Men like doing. Since in today's competitive world both the parents have to work they need a secure place to leave behind their children who will take care of them and parents can also relax without being worried all the time. In this job you don't require any degree or qualifications. You only have to know how to take care of children. Parents are happy to pay handsome salary and you can also earn a lot without putting too much of an effort.

    For those who have a garden or an open space at your disposal and are also interested in gardening can go for this method of earning money. If given proper time and efforts nursery business can flourish very well and you will earn handsomely. But just as all jobs establishing it will be a bit difficult but the end results are outstanding.

    Freelance can be in different wings. Either you can be a freelance reporter or a freelance photographer. You can also do designing or be in the advertising field doing project on your own. Being independent and working independently will depend on your field of work and the availability of its worth in the market. If you like doing jewellery designing you can do that at home totally independently. You can also work on freelancing as a marketing executive working from home. Wanna know more, email us on and we will send you information on how you can actually work as a marketing freelancer.

    Internet related work
    This is a very vast field and here sky is the limit. All you need is a computer and Internet facility. Whatever field you are into work at home is perfect match in the software field. You can match your time according to your convenience and complete whatever projects you get. To learn more about how to work from home, contact us today on workfromhome.otr214423@gmail.comand our team will get you started on some excellent work from home projects.

    Diet food
    Since now a days Women & Men are more conscious of the food that they eat hence they prefer to have homemade low cal food and if you can start supplying low cal food to various offices then it will be a very good source of income and not too much of efforts. You can hire a few ladies who will help you out and this can be a good business.

    Thus think over this concept and go ahead.

  3. Hi, thanks for the article and the fix for the SetScale error. Did you notice if the opposite direction of 0 ° match with 180°? My sensor keeps returning about 205° in that position. Any ideas about whats going on?

  4. how to calculate the angle of inclination, for my city is:
    Magnetic declination: + 0 ° 10 'EAST
    Declination is POSITIVE

  5. I refer to this value
    declinationAngle float = 0.0404;
    your article is very good

  6. Declination is not always added to get the true bearing. If your declination is E, the magnetic bearing will be larger than true, so subtract declination ("-=") to get true bearing.. This does make a difference.

  7. Using two of these can you get a heading and declination?

  8. hi the code doesn't work
    Error compiling
    Arduino: 1.6.6 Hourly Build 2015/10/14 10:42 (Windows 7), Board: "Arduino Mega ADK"

    Build options changed, rebuilding all
    fatal error: WProgram.h: No such file or directory



    compilation terminated.

    exit status 1
    Error compiling.

    This report would have more information with
    "Show verbose output during compilation"
    enabled in File > Preferences.

    1. Have you install his library?

    2. I got same problem.. then I downloaded the same code from here it works perfectly.. I did not know why these kind of things happen because these all are same code.. no idea

    3. This comment has been removed by the author.

    4. This comment has been removed by the author.

    5. I received the same error when compiling - From another forum tried a suggestion to change the include statement Wprogram.h in the cpp file to Arduino.h. Used a text editor to modify the cpp file in the arduino libraries folder and compiled and that fixed the compile error.

  9. i got a problem, my degree values only 221.something and 220.something, when I rotate the compass 360 degrees, the value is still the same, 221.something and 220.something, can you help me?

  10. "For" cycle I would like to read the data multiple times in a row.
    Unfortunately, the cycle read datas only once, but several times. Can you help me fix it?
    correct: 10, 12, 9, 11
    incorrect: 10, 10, 10, 10

    1. :) CODE:
      MagnetometerRaw raw = compass.ReadRawAxis();
      MagnetometerScaled scaled = compass.ReadScaledAxis();
      for(int i=0;i<5;i++){
      switch(i) {
      case 0:
      sXTomb[0] = scaled.XAxis;
      case 1:
      sXTomb[1] = scaled.XAxis;
      case 2:
      sXTomb[2] = scaled.XAxis;
      case 3:
      sXTomb[3] = scaled.XAxis;
      case 4:
      sXTomb[4] = scaled.XAxis;

  11. I am using HMC5883L for my project. I have interfaced it with the arduino and executed the program given in the website. But the problem is it is showing the same angle (66.68) when I rotate & if I do it in other places I am facing the same problem. I have also added declination angle of that place. So please help me how to make it work properly.

  12. I am using HMC5883L for my project. I have interfaced it with the arduino and executed the program given in the website. But the problem is it is showing the same angle (66.68) when I rotate & if I do it in other places I am facing the same problem. I have also added declination angle of that place. So please help me how to make it work properly.

  13. You have really shared a informative and interesting blog post with people..
    used measurement equipment

  14. What is the reason of using scaled.XAxis and not the raw values?

    I mean, for the calculation of the headline, the operation is arc_tan and this the same for atan(y*scale / x*scale) and atan(y/x).

    I believe the scale is important when you really want to measure the magnitude of the magnetic vector components.

    Any thoughts?

  15. Wonderfull !! thank you so much !!

  16. i can't open the link for the library, can someone give me the correct link?

  17. Can you please explain what is x-axis,y-axis referenced to?

  18. having problem with wire.h library

  19. Nice and Lovely post. Kindly Visit us @ Gauss Meter

  20. Hi. I'm using GY-273 module (HMC5883L based shield). I can't read information from this module.
    I ran the sketch but the information I receive is:
    0 0 0. If I unplug any SDA or SCL pin, the information printed is -1 -1 -1. This means I have communication.
    I tried many libraries and arduinos and shields.
    Can someone help me, please: Thanks a lot.

    1. i'm experiencing the same thing. did u find any way out?
      please revert!

  21. I am using LSM303 sensor. It says that internally it uses HMC5883 sensor. I compiled it for Arduino nano and compiler refused. What is the reason, the library is not working with nano? original 303 library code is running well on sensor so wiring is correct.

  22. hi. perfect. but i have problems reading angles from 270 to 360. rest of quadrnts ok. Any help?

  23. homemade geomagnetic magnetometer

  24. Hi, I cannot install library correctly, can you tell me how to install correctly and it is not ZIP , it is RAR file.

  25. I really like your guide. Maybe you can take a look at this store selling the HMC5883L :

  26. Attractive, post. I just stumbled upon your weblog and wanted to say that I have liked browsing your blog posts. After all, I will surely subscribe to your feed, and I hope you will write again soon! paykwik kart

  27. I am using this code but error occurred and i am unable to figure it out

    "variable or field 'Output' declared as void."
    please help

    1. Yeah, I'm getting this, too. Did you find a solution?

  28. This comment has been removed by the author.

  29. Hello, is there any chance you have some spare HMC5883L CJ-149 modules still laying around. I would be willing to pay for them.

  30. Nice information, valuable and excellent design, as share good stuff with good ideas and concepts, lots of great information and inspiration, both of which I need, thanks to offer such a helpful information here.

  31. Spank me. It’s the only way I learn. Hey, i am looking for an online sexual partner ;) Click on my boobs if you are interested (. )( .)

  32. cricket bat Melbourne
    Old handle removed, shoulder damage repaired, new handle fitted in blade, shaped, bound, light sand and oil if required. Stickers can be reapplied on splice area free of charge if they are. provided

  33. This code is a piece of shit. It doesn't work.