- Sun Apr 01, 2018 5:08 pm
#75067
Anyone trying to make a compass chip work with their arduino and frustrated with an HMC5883L that is actually a QMC5883L (i.e. the thing you bought that doesn't work with HMC588L test code) try this code (works with Arduino Uno). Its an edited version of stuff I found on the net, correcting a few mistakes in register references.
//There are several differences between the QMC5883L and the HMC5883L chips
//Differences in address: 0x0D for QMC5883L; 0x1E for HMC5883L
//Differences in register map (compare datasheets)
//Output data register differences include location of x,y,z and MSB and LSB for these parameters
//Control registers are also different (so location and values for settings change)
#include <Wire.h> //I2C Arduino Library
#define addr 0x0D //I2C Address for The QMC5883L (0x1E for HMC5883)
double scale=1.0;
void setup() {
double scaleValues[9]={0.00,0.73,0.92,1.22,1.52,2.27,2.56,3.03,4.35};
scale=scaleValues[2];
//initialize serial and I2C communications
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(addr); //start talking to slave
Wire.write(0x0B);
Wire.write(0x01);
Wire.endTransmission();
Wire.beginTransmission(addr); //start talking to slave
Wire.write(0x09);
Wire.write(0x1D);
Wire.endTransmission();
}
void loop() {
int x, y, z; //triple axis data
//Tell the QMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x00); //start with register 00H for QMC5883L
Wire.endTransmission();
double bearing=0.00;
//Read the data.. 2, 8 bit bytes for each axis.. 6 total bytes
Wire.requestFrom(addr, 6);
//read 6 registers in order; register location (i.e.00H)indexes by one once read
if (6 <= Wire.available()) {
//note the order of following statements matters
//as each register will be read in sequence starting from data register 00H to 05H
//where order is xLSB,xMSB,yLSB,yMSB,zLSB,zMSB
//this is different from HMC5883L!
//data registers are 03 to 08
//where order is xMSB,xLSB,zMSB,zLSB,yMSB,yLSB
x = Wire.read(); //LSB x;
x |= Wire.read()<<8; //MSB x; bitshift left 8, then bitwise OR to make "x"
x*=scale;
y = Wire.read(); //LSB y
y |= Wire.read()<<8; //MSB y;
y*=scale;
z = Wire.read(); //LSB z; irrelevant for compass
z |= Wire.read()<<8; //MSB z;
z*=scale;
bearing=180*atan2(y,x)/3.141592654;//values will range from +180 to -180 degrees
bearing +=5+(58/60);//Adjust for local magnetic declination
}
// Show Values
Serial.print("X Value: ");
Serial.print(x);
Serial.print(" - Y Value: ");
Serial.print(y);
//Serial.print(" - Z Value: ");
//Serial.print(z);
Serial.print(" - Bearing: ");
Serial.println(bearing);
delay(500);
}