How it works...

The script is based on the XLoBorg library available for the XLoBorg module, except that we use WiringPi2, which is Python 3-friendly, to perform the I2C actions. Just like our motor/servo drivers, we also define it as a class, so that we can drop it into our code and easily replace it with alternative devices if required.

We import wiringpi2, time, and a library called struct (which allows us to quickly unpack a block of data read from the device into separate items).

We create the compass class, which will include the __init__(), initCompass(), and readCompassRaw() functions. The readCompassRaw() function is the equivalent of the standard XLoBorg ReadCompassRaw() function provided by their library.

The __init__() function sets up the I2C bus with wiringpi2 and registers the degMAG device on the bus address 0x0E. The initCompass() function sets the CTRL_REG1 and CTRL_REG2 registers of the device with the settings required to quickly get raw readings from the device.

More details on the MAG3110 registers are available at http://www.freescale.com/files/sensors/doc/data_sheet/MAG3110.pdf.

The readCompassRaw() function reads the data registers of the device in a single block (using the custom function readBlockData()). It reads all of the 18 registers of the device (0x00 through to 0x11). The sensor readings we need are contained within the registers 0x01 to 0x06, which contain the x, y, and z readings, split into upper and lower bytes (8-bit values). The struct.pack() and struct.unpack() functions provide an easy way to package them together and re-split them as separate words (16-bit values).

We can test our script by creating a myCompass object from the compass class and reading the sensor values using myCompass.readCompassRaw(). You will see the raw x, y, and z values from the device, just as you would from the standard XLoBorg library.

As you will find, these values aren't of much use on their own, since they are uncalibrated
and only give you RAW readings from the magnetometer. What we need is a far more useful angle, relative to magnetic north (see the following There's more... section for details on how to do this).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.236.70