Hey everyone I'm a beginner in Arduino and recently i'm doing a project trying to find magnetic field strength with a magneto resistive sensor (QMC5883L) but I think I got a problem because value of M its not correct ,its very high and keeps changing when I rotate my sensor, as I know it should be constant unless a magnet is near the sensor, can anyone help me realize what am I missing?
Any help would be appreciated!
This is the code:
#include <Wire.h> //I2C Arduino Library
#define addr 0x0D //I2C Address for The HMC5883
int minX = -3105;
int maxX = 6685;
int minZ = 0;
int maxZ = 16490;
int minY = -8955;
int maxY = 362;
double xx=0,zz=0,yy=0;
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(addr); //start talking
Wire.write(0x0B); // Tell the HMC5883 to Continuously Measure
Wire.write(0x01); // Set the Register
Wire.endTransmission();
Wire.beginTransmission(addr); //start talking
Wire.write(0x09); // Tell the HMC5883 to Continuously Measure
Wire.write(0x1D); // Set the Register
Wire.endTransmission();
}
void loop() {
int x, y, z; //triple axis data
//Tell the HMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x00); //start with register 3.
Wire.endTransmission();
//Read the data.. 2 bytes for each axis.. 6 total bytes
Wire.requestFrom(addr, 6);
if (6 <= Wire.available()) {
x = Wire.read(); //MSB x
x |= Wire.read() << 8; //LSB x
z = Wire.read(); //MSB z
z |= Wire.read() << 8; //LSB z
y = Wire.read(); //MSB y
y |= Wire.read() << 8; //LSB y
}
int xoff=(minX+maxX)/2;
int zoff=(minZ+maxZ)/2;
int yoff=(minY+maxY)/2;
float Xavg_delta=(maxX-minX)/2;
float Zavg_delta=(maxZ-minZ)/2;
float Yavg_delta=(maxY-minY)/2;
int avg_delta=(Xavg_delta+Zavg_delta+Yavg_delta)/3;
float Xscale=(avg_delta/Xavg_delta);
float Zscale=(avg_delta/Zavg_delta);
float Yscale=(avg_delta/Yavg_delta);
float Xc=(x-xoff)*Xscale;
float Zc=(z-zoff)*Zscale;
float Yc=(y-yoff)*Yscale;
float XXX=Xc/12000;
float ZZZ=Zc/12000;
float YYY=Yc/12000;
float M=sqrt(XXX*XXX+ZZZ*ZZZ+YYY*YYY);
Serial.print("X: ");
Serial.print(Xc);
Serial.print("Z: ");
Serial.print(Zc);
Serial.print("Y: ");
Serial.print(Yc);
Serial.print(" M: ");
Serial.print(M);
Serial.print("\n");
delay(500);
}
and this are values I get:
X: -12.12 Z: -9486.88 Y: 6161.23 M: 0.94
X: -21.81 Z: -9480.41 Y: 6184.15 M: 0.94
X: -9.69 Z: -9499.11 Y: 6308.96 M: 0.95
X: -39.9 Z: -9501.27 Y: 6241.46 M: 0.95
X: -1114.90 Z: -9662.43 Y: 5786.82 M: 0.94
X: -1617.82 Z: -9530.05 Y: 5714.23 M: 0.94
X: -306.60 Z: -9583.29 Y: 5900.16 M: 0.94
X: 448.38 Z: -9029.30 Y: 6296.22 M: 0.92
X: 427.78 Z: -9008.44 Y: 6167.60 M: 0.91
X: -135.73 Z: -8773.89 Y: 5369.11 M: 0.86
X: -671.36 Z: -8540.07 Y: 5283.78 M: 0.84
X: -539.27 Z: -8583.23 Y: 5286.33 M: 0.84
X: 8.48 Z: -9181.83 Y: 5566.50 M: 0.89