我正在开发基于arduino的GPS导航机器人,我正在使用hmc5883-l指南针,已经对指南针进行了校准,但问题是它显示方向错误,例如,如果我的机器人必须向西移动270度,我的机器人将进行校正以匹配270度,但机器人的270度不是实际的270度。
我正在使用此代码
#include <Wire.h>
#include <HMC5883L.h>
HMC5883L compass;
void setup()
{
Serial.begin(9600);
Serial.println("Initialize HMC5883L");
while (!compass.begin())
{
Serial.println("Could not find a valid HMC5883L sensor, check wiring!");
delay(500);
}
compass.setRange(HMC5883L_RANGE_1_3GA);
compass.setMeasurementMode(HMC5883L_CONTINOUS);
compass.setDataRate(HMC5883L_DATARATE_30HZ);
compass.setSamples(HMC5883L_SAMPLES_8);
compass.setOffset(72,177);
}
void loop()
{
Vector norm = compass.readNormalize();
float heading = atan2(norm.YAxis, norm.XAxis);
float declinationAngle = (2 + (8 / 60.0)) / (180 / M_PI);
heading += declinationAngle;
if (heading < 0)
{
heading += 2 * PI;
}
if (heading > 2 * PI)
{
heading -= 2 * PI;
}
float headingDegrees = heading * 180/M_PI;
Serial.print(" Heading = ");
Serial.print(heading);
headingDegrees=360-headingDegrees; //because compass is upside down
Serial.print(" Degrees = ");
Serial.print(headingDegrees);
Serial.println();
delay(100);
}
机器人指向西方向(270度)时输出
Heading = 0.18 Degrees = 349.68
Heading = 0.17 Degrees = 350.19
Heading = 0.16 Degrees = 350.74
Heading = 0.19 Degrees = 349.34
Heading = 0.19 Degrees = 349.22
Heading = 0.17 Degrees = 350.51
Heading = 0.18 Degrees = 349.66
Heading = 0.18 Degrees = 349.95
Heading = 0.20 Degrees = 348.71
Heading = 0.16 Degrees = 350.74
Heading = 0.18 Degrees = 349.90
Heading = 0.19 Degrees = 348.89
此时,度数必须为270,但约为348