Skip to main content
3 of 4
added 753 characters in body

Connecting the HMC6352 compass module to a Raspi using I2C

I am trying to connect a HMC6352 compass module to my Raspberry Pi.

According to the datasheet I need to send an "A" for a read command. However, I am somewhat new to I2C and do not know how to accomplish this. I would like to do the coding in Python.

I know I have set up I2C correctly, and that the compass is correctly connected to the Pi, because I can see it when I run i2cdetect:

pi@raspberrypi ~ $ sudo i2cdetect -y 0
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- 21 -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- --    

You can see the compass on address 21, although the documentation says the default address is 42.

I am running Adafruit's Occidentals V2 for my OS.

Could anyone show me some example Python code that returns the current reading from the compass?

EDIT: I may have made some progress. Using the python library quick2wire I have successfully connected to the compass:

>>> from quick2wire.i2c import I2CMaster, writing_bytes, reading
>>> address = 0x21  # detected using `sudo i2cdetect -y 0`
>>> cmd = 0x41  # 'A'
>>> master = I2CMaster()
>>> master.transaction(writing_bytes(address, cmd))
[]
>>> master.transaction(reading(address, 2))
[b'\x03s']

Repeatedly running the last two lines seems to produce different values when I move the compass. The numbers also seem self consistent. By this I mean the same byte value appears if I move the compass away from and back to a direction.

How do I convert this bytes object to a compass heading value?