From Swordfish Wiki

SwordfishUser: DevantechCMPS03MagneticCompassModule


Devantech CMPS03 Magnetic Compass Module

A module to read the magnetic bearing from a Devantech CMPS03 Magnetic Compass Module. The bearing can be read as a word using GetBearingAsWord, giving a value from 0 - 3599 (representing the bearing in tenths of a degree), or as a byte using GetBearingAsByte, giving a value from 0 - 255 to represent 0 - 360 degrees.

Example Code

Device = 18F452
Clock =  20

#option I2C_SCL = PORTD.0
#option I2C_SDA = PORTD.1

Include "CMPS03.bas"
Include "Convert.bas"
Include "USART.bas"

Dim Bearing As Word

// program start...
DelayMS(10)
USART.SetBaudrate(br115200)

Repeat
   Repeat
      Bearing = CMPS03.GetBearingAsWord
   Until Bearing < 3600
   USART.Write("Bearing = ", DecToStr(Bearing / 10, 3), ".", DecToStr(Bearing Mod 10, 1), 13, 10)
   DelayMS(200)
Until False

Module Code

{
*****************************************************************************
*  Name    : CMPS03.BAS                                                     *
*  Author  : S Wright                                                       *
*  Notice  : Copyright (c) 2007 S Wright                                    *
*          : All Rights Reserved                                            *
*  Date    : 06/10/2007                                                     *
*  Version : 1.0                                                            *
*  Notes   : A module for reading from a Devantech CMPS03 Magnetic Compass  *
*          : Module                                                         *
*          :                                                                *
*****************************************************************************
}
Module CMPS03

#option I2C_SCL = PORTC.3
#option I2C_SDA = PORTC.4

Include "SI2C.bas"

// target CMPS03 compass module device...
Const SI2C_CMPS03 = $C0 

Function GetRegister(pReg As Byte) As Byte
   SI2C.Start                          
   SI2C.WriteByte(SI2C_CMPS03 + 0)  
   DelayUS(50)
   SI2C.WriteByte(pReg)       
   DelayUS(50)
   SI2C.Restart                         
   SI2C.WriteByte(SI2C_CMPS03 + 1)
   DelayUS(50)
   Result = SI2C.ReadByte(I2C_NOT_ACKNOWLEDGE)
   SI2C.Stop
End Function

Public Function GetBearingAsByte() As Byte
   Result = GetRegister(1)
End Function

Public Function GetBearingAsWord() As Word
   Result.Bytes(1) = GetRegister(2)
   Result.Bytes(0) = GetRegister(3)  
End Function

// init

SI2C.Initialize
Retrieved from http://www.sfcompiler.co.uk/wiki/pmwiki.php?n=SwordfishUser.DevantechCMPS03MagneticCompassModule
Page last modified on October 23, 2007, at 08:44 PM