1

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?

1 Answer 1

2

I figured out how to do this using the quick2wire python library. Note it must be run using python3

#!/usr/bin/env python3                                                                          

from quick2wire.i2c import I2CMaster, writing_bytes, reading                  
import time                                                                   

address = 0x21  # found using `sudo i2cdetect -y 0`                                                         
cmd = 0x41  # 'A' means read                                                     

with I2CMaster() as master:                                                   

    while True:                                                               
        master.transaction(writing_bytes(address, cmd))                       
        raw_bytes = master.transaction(reading(address, 2))[0]                

        #Shift the first byte up by 8 bits and add it to the second
        #The result is in 10ths of degrees, so divide by 10 to get
        #degrees.
        heading = (raw_bytes[0] * 2**8 + raw_bytes[1]) / 10                   
        print(heading)                                                        

        time.sleep(.2)   
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.