Configure, read data & calibrate the HMC5883L digital compass using Python
 
As in my other blogs, this one just contains a lot of information that can be found elsewhere on the web. I just structured it to make it easy to use for beginning robot hobbyists. 
 
Connecting the compass is quite simple. When mounting the sensor to the bot, be aware of the x-y-z marker on the sensor and assure that the x-> points towards the front of the bot.

The compass uses the I2C protocol. Connect the sensor to the (I2C-) GPIO pins on the Pi as follows:
Connect VCC to pin-1 (3.3.V)
Connect SDA to pin-3 (SDA = System Data)
Connect SCL to pin-5 (SCL = System Clock)
Connect GND to pin 7 (GND)
 
First of all the Raspberry Pi needs to be configured for using the I2C protocol. This is disabled by default on the Raspberry. You’ll find an excellent tutorial at:  

https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c

When testing the I2C connection as explained at the end of the Adafruit lesson, the 0x1e address will most likely be shown for the HMC5883L sensor. If you get a different address you’ll have to change the address variable in the scripts.
 
To calibrate the compass the bot will have to be turned several times. This can be done by hand. I used a rotating snack display to make turning the bot, while keeping it horizontal, easy. The picture below is of a rather bad quality, but it illustrates what I was aiming for.
 
The next step is reading and displaying data from the sensor. For this I used a very simple script which can be found here:

https://bitbucket.org/RoboBasics/raspberry-robo-cars/src/d4fef2c5aad183ce186c378d9c89f618bddfd032/Handy%20stuff/HMC5883L_calibrate_step_1.py?at=master  

How to use the sensor registers for binary reading and writing can be found in the sensor data sheet and in the script. I won’t go into that details here. The script initializes the sensor as follows:
8 samples at 15 Hz, LSb gain 1.5 (default), Gauss 1090 (default), continuous sampling, scaling 0.92

If you don’t want to dive into the sensor characteristics, just leave the values as in the script. They are pretty generic and will suffice for almost all situations.
 
Now the script reads the x, y and z registers, calculates the arctangent of x and y and converts the outcome into degrees.
 
Just run the script and you’ll get a first bearing e.g. 46.53891942 (46° 53’ 89.2”)

Start rotating the bot until you get close to 0 degrees. Then rotate it through four 90° positions, reading the sensor data at every step. Most probably you might see that the values deviate and are not fully right.
 
Continued in next blog:

Configure, read data & calibrate the HMC5883L digital compass using Python – part 2

https://plus.google.com/113179308235478830494/posts/cPCrDT9EgCp
Photo
Shared publicly