I've got a cmps10 compass module hooked up to my arduino due through a logic level converter. I am writing code to convert the raw magnetometer readings into a bearing that I can use but have run into a huge problem. My bearings are all funky for some reason. They are totally unrelated to the actual bearing of the robot. I know the sensor is fine because I am able to get the tilt compensated reading from it and it works great. One thing I noticed is that the magnetometer reading on the X-axis is always positive could this be the problem? The X-axis high byte generally between 0x00 and 0x03. My code is below (i2cBus = &Wire)
i2cBus->beginTransmission(I2C_Address);
i2cBus->write(byte(10));
i2cBus->endTransmission();
i2cBus->requestFrom(I2C_Address, 4);
xMagHighByte = i2cBus->read();
xMagLowByte = i2cBus->read();
yMagHighByte = i2cBus->read();
yMagLowByte = i2cBus->read();
xMag = short(xMagHighByte<<8);
xMag |= xMagLowByte;
yMag = short(yMagHighByte<<8);
yMag |= yMagLowByte;
if(yMag!=0){
magBearing = (atan2(xMag,yMag)*180.0)/3.141592654;
}
else if(xMag>0) magBearing=0.0;
else if(xMag<0) magBearing=180.0;
else magBearing = 1000;
if(magBearing < 0) magBearing+=360;
magBearing=360-magBearing;
return magBearing;