Python Forum

Full Version: Compass Calibrate
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello guys, i need somebody who can explain how to use compass CMPS with python on raspi3 . I have compass module CMPS-12 but i dont have the library and Example, so i dont know how to use/calibrate my compass on python. Anyone knows? Please help :( thanks . :)
I'm using the CMPS11/12. I use the 'horizontal only operation' of this device: CMPS11 I2C Mode

I wrote for myself a little script to calibrate the compass. The outputs I'm controlling are connected to a drive (H-Bridge), which rotates clockwise.

#!/usr/bin/env python

import smbus
import time
import RPi.GPIO as GPIO


def start_calibration(bus):
    command = bytearray([0xF0, 0xF5, 0xF7])
    for c in command:
        bus.write_byte_data(0x60, 0x0, c)
        time.sleep(0.02)

def stop_calibration(bus):
    bus.write_byte_data(0x60, 0x0, 0xF8)

def init_gpio():
    GPIO.setwarnings(False)
    pins = [17, 18, 22, 27]
    GPIO.setmode(GPIO.BCM)
    for pin in pins:
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, False)
    return GPIO.PWM(18, 1000)

def start_cw_turn(pwm):
    GPIO.output(22, True)
    GPIO.output(17, True)
    pwm.start(10)

def stop(pwm):
    GPIO.output(22, False)
    GPIO.output(17, False)
    pwm.stop()


def main():
    bus = smbus.SMBus(1)
    print('Init GPIO')
    pwm = init_gpio()
    print('Start calibration')
    start_calibration(bus)
    print('Start motor')
    start_cw_turn(pwm)
    print('Sleeping one minute')
    time.sleep(120)
    print('Stopping calibration')
    stop_calibration(bus)
    print('Stopping motor')
    stop(pwm)

if __name__ == '__main__':
    main()
If you want to do the conversion of azimuth by yourself:
class Compass:
    def __init__(self, offset=0.0, bus=1, device=0x60):
        self.offset = offset
        self.bus = smbus.SMBus(bus)
        self.device = device

    @property
    def azimuth(self):
        high = self.bus.read_byte_data(self.device, 0x2) << 8
        low = self.bus.read_byte_data(self.device, 0x3)
        angle = (high + low) / 10.0
        return (angle + self.offset) % 360