获取原始数据,然后计算
附件是使用了OLED 0.96来做的指南针,虽然YZ轴没啥用,但是还是做了处理;
和iphone对比,基本上做到了5度之内的偏差;
Multiple_Read_QMC5883(BUF);
magx=BUF[1] << 8 | BUF[0]; //Combine MSB and LSB of X Data output register 最高有效位
magy=BUF[3] << 8 | BUF[2]; //Combine MSB and LSB of Y Data output register
magz=BUF[5] << 8 | BUF[4]; //Combine MSB and LSB of Z Data output register
if(magx>0x7fff)magx-=0xffff;
if(magy>0x7fff)magy-=0xffff;
if(magz>0x7fff)magz-=0xffff;
magx=magx-offsetX;magy=magy-offsetY;magz=magz-offsetZ;
Angle_XY= atan2((double)magy,(double)magx) * (180 / 3.14159265) + 180; //计算XY平面角度
Angle_XZ= atan2((double)magz,(double)magx) * (180 / 3.14159265) + 180; //计算XZ平面角度
Angle_YZ= atan2((double)magz,(double)magy) * (180 / 3.14159265) + 180; //计算YZ平面角
当然这还是不够的,因为磁场便宜,或当地磁场问题会造成,xyz拟合的时候出现椭圆,所以要修正;
Multiple_Read_QMC5883(BUF); //连续读出数据,存储在BUF中
X=BUF[1] << 8 | BUF[0]; //Combine MSB and LSB of X Data output register 最高有效位
Y=BUF[3] << 8 | BUF[2]; //Combine MSB and LSB of Y Data output register
Z=BUF[5] << 8 | BUF[4]; //Combine MSB and LSB of Z Data output register
if(X>0x7fff)X-=0xffff;
if(Y>0x7fff)Y-=0xffff;
if(Z>0x7fff)Z-=0xffff;
if (X > xMax)
xMax = X;
if (X < xMin )
xMin = X;
if(Y > yMax )
yMax = Y;
if(Y < yMin )
yMin = Y;
if(Z > zMax )
zMax = Z;
if(Z < zMin )
zMin = Z;
if(abs(xMax - xMin) > 0 )
offsetX = (xMax + xMin)/2;
if(abs(yMax - yMin) > 0 )
offsetY = (yMax + yMin)/2;
if(abs(zMax - zMin) > 0 )
offsetZ = (zMax +zMin)/2;
Keil代码下载:
51单片机代码.7z
(57.28 KB, 下载次数: 199)
|