Instructables

Step 5: Example 1: CMPS03 Compass Module

Picture of Example 1: CMPS03 Compass Module
We now have everything ready to start using I2C! 

To use the CMPS03 compass module, connect the power to V+ and 0V, from the Pi. I used the 5V line, which they recommend not doing because it might damage your pi, It worked for me, and has caused now damage, but I am not responsible if your's fries. 

Then, connect the SDA and SCL lines to the Pi SDA and SCL, and you are ready to roll. The wiring diagram is shown at http://www.robot-electronics.co.uk/htm/cmps3tech.htm. 

When you have connected it, run the command "i2cdetect -y 0". In my case, this returned: 

       0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: 60 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --


This shows that the module is on address 0x60.  You then need the following python file:

import smbus
import time
bus = smbus.SMBus(0)
address = 0x60

def bearing255():
        bear = bus.read_byte_data(address, 1)
        return bear

def bearing3599():
        bear1 = bus.read_byte_data(address, 2)
        bear2 = bus.read_byte_data(address, 3)
        bear = (bear1 << 8) + bear2
        bear = bear/10.0
        return bear

while True:
        bearing = bearing3599()     #this returns the value to 1 decimal place in degrees. 
        bear255 = bearing255()      #this returns the value as a byte between 0 and 255. 
        print bearing
        print bear255

        time.sleep(1)

This program should be saved as anything, but add ".py" on the end. Then, run the command with sudo python whateveryoucalledit.p and you should get values written to your screen in a long list. 
 
Remove these adsRemove these ads by Signing Up
moshtaghioun8 months ago

TNX for the great instruction but 1 question

i didn't understand if the 5V i2c device has damaged your device or not ,

trollies1 year ago
When you do:

bear2 = bus.read_byte_data(address, 3)
bear = (bear1 << 8) + bear2
bear = bear/10.0
return bear....
why do you divide by 10? I am assuming you have a signed 15 bit number and you are getting rid of the last 0? Why not use >> 1?