ive been working on a project which requires magnetometer and the coding im doing on it is low level. so, im facing an issue regarding its calibration as im rotating my qmc5883l chip im getting a heading between 22 degrees to 60 degrees something and the thing is like if i keep on rotating after these values for ex when it reaches 22 degrees and i keep rotating it actually starts increasing the angle linearly again like 23, 24....and so any fixes or a way to calibrate could be helpful
#include <Wire.h>
#define QMC5883_ADDRESS 0x0D
int16_t xread, yread, zread;
float xout, yout, zout;
void setup() {
Serial.begin(9600);
Wire.begin();
// Control register 1: mode = continuous, output data rate = 10Hz, RNG = 8G, OSR = 512
Wire.beginTransmission(QMC5883_ADDRESS);
Wire.write(0x09);
Wire.write(0b00010101); // OSR=512, RNG=8G, ODR=10Hz, continuous mode
Wire.endTransmission();
// Soft reset (optional)
//Wire.beginTransmission(QMC5883_ADDRESS);
//Wire.write(0x0A);
//Wire.write(0x80);
//Wire.endTransmission();
}
void loop() {
// Set register pointer to data output
Wire.beginTransmission(QMC5883_ADDRESS);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(QMC5883_ADDRESS, 6);
if (Wire.available() == 6) {
xread = Wire.read() | (Wire.read() << 8);
yread = Wire.read() | (Wire.read() << 8);
zread = Wire.read() | (Wire.read() << 8);
xout = (float)xread / 30.0;
yout = (float)yread / 30.0;
zout = (float)zread / 30.0;
float heading = atan2(yout, xout) * 180 / PI;
if (heading < 0) heading += 360;
//Serial.print("Xraw: "); Serial.print(xread);
//Serial.print(" Yraw: "); Serial.print(yread);
//Serial.print(" Zraw: "); Serial.print(zread);
Serial.print("Xout: "); Serial.print(xout);
Serial.print(" Yout: "); Serial.println(yout);
Serial.print(" Heading: "); Serial.print(heading); Serial.println("°");
} else {
Serial.println("Sensor not responding or insufficient data.");
}
delay(500);
}