stm32的hmc5883校正代码分享:
- void calibrateMag(int * offsetX,int * offsetY,int * offsetZ,float * y_gain)
- {
- short int x,y,z,i; //三轴数据
- int xMax, xMin, yMax, yMin, zMax, zMin;
- //初始化
- Get_mag_ADC(&x,&y,&z);
- xMax=xMin=x;
- yMax=yMin=y;
- zMax=zMin=z;
- * offsetX =0;
- * offsetY =0;
- * offsetZ =0;
-
- for( i=0;i<250;i++)
- {
- Get_mag_ADC(&x,&y,&z);
- // 计算最大值与最小值
- // 计算传感器绕X,Y,Z轴旋转时的磁场强度最大值和最小值
- 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;
-
- delay_ms(100);
-
- if(i%20 == 0)
- {
- printf("\n xMax = %d ",xMax);
- printf("xMin = %d --",xMin);
- printf(" yMax = %d ",yMax);
- printf("yMin = %d \n",yMin);
- }
- }
复制代码 主函数:- int main(void)
- {
- //double angle;
- delay_init(); //延时函数初始化
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//设置中断优先级分组为组2:2位抢占优先级,2位响应优先级
- uart_init(115200); //串口初始化为115200
- IIC_Init();
- Init_HMC5883();
- delay_ms(500);
- calibrateMag(& offsetX,& offsetY,& offsetZ,& Y_Gain);
- // usmart_init(72);
- while(1)
- {
- ///////////////////////////////////////////////////////////////////////////////
- // a++;//a 溢出 : 32766,32767,-32768,-32767,-32766....
- // a--;//a : 2,1,0,-1,-2,....
- // short int :-32768<a<32767 占内存16位
- // int : 占内存32位
- ///////////////////////////输出方式0////////////////////////////////////
- Get_mag_ADC(&x,&y,&z);
- angle=atan2((double)(y-offsetY)*Y_Gain,(double)(x-offsetX))*(180 / 3.14159265)+180;
- //磁偏角矫正
- angle = angle - MagnetcDeclination + 180;
- if(angle < 0) angle += 360;
- else if(angle >360) angle -= 360;
-
- printf("\n x = %d y = %d z = %d ",x,y,z);
- printf("水平角度= %.2f 增益 = %f.3\n",angle,Y_Gain);
- delay_ms(300);
- /////////////////////输出方式一/////////////////////////
- // angle= Get_Compass_Angle();
- // delay_ms(300);
- // x = BUF[0] << 8 | BUF[1];
- // y = BUF[2] << 8 | BUF[3];
- // z = BUF[4] << 8 | BUF[5];
- // printf("\n x = %d y = %d z = %d ",x,y,z);
- // printf("角度1= %f \n",angle);
- ////////////////////输出方式二/////////////////////////
- // HMC5883_ReadXYZ(&x,&y,&z);
- // angle=atan2((double)y,(double)x)*(180 / 3.14159265)+180;
- // delay_ms(300);
- // printf("\n x1 = %d y1 = %d z1 = %d ",x,y,z);
- // printf("角度2= %f \n",angle);
- //
- ///////////////////////////////////////////////////////
- }
- }
复制代码
全部资料51hei下载地址:
HMC5883数据罗盘矫正.rar
(363.06 KB, 下载次数: 256)
|