2、陀螺仪初始化代码
- /**
- * 功能:初始化MPU6050
- * 入口参数:无
- * 返回值:0,成功;其他,错误
- */
- u8 MPU_Init(void)
- {
- u8 res;
- GPIO_InitTypeDef GPIO_InitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOA,ENABLE);
-
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOA,&GPIO_InitStructure);
-
- GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable,ENABLE);//禁止JTAG,使PA15变为普通IO
-
- MPU_AD0_CTRL = 0;//控制MPU6050的AD0为低电平,从机地址=0x68;
- // 高电平, 0x69;
- MPU_IIC_Init();
- MPU_Write_Byte(MPU_PWR_MGMT1_REG,0x80);//复位从机
- delay_ms(100);
- MPU_Write_Byte(MPU_PWR_MGMT1_REG,0x00);//唤醒从机
- MPU_Set_Gyro_Fsr(3);//陀螺仪传感器 +-2000dps
- MPU_Set_Accel_Fsr(0);//加速度传感器 +-2g
- MPU_Set_Rate(50);
- MPU_Write_Byte(MPU_INT_EN_REG,0x00);//关闭所有中断
- MPU_Write_Byte(MPU_USER_CTRL_REG,0x00);//IIC主模式关闭
- MPU_Write_Byte(MPU_FIFO_EN_REG,0x00);//关闭FIFO
- MPU_Write_Byte(MPU_INTBP_CFG_REG,0x80);//INT低电平有效
- res = MPU_Read_Byte(MPU_DEVICE_ID_REG);
- if(res == MPU_ADDR)
- {
- MPU_Write_Byte(MPU_PWR_MGMT1_REG,0x01);//设置CLKSEL PLL X轴为参考
- MPU_Write_Byte(MPU_PWR_MGMT2_REG,0x00);//加速度计和陀螺仪使能
- MPU_Set_Rate(50);
- }
- else
- return 1;
- return 0;
- }
- /**
- * 功能:设置陀螺仪传感器满量程范围
- * 入口参数:fsr,0,+-250dps
- * 1,+-500dps
- * 2,+-1000dps
- * 3,+-2000dps
- * 返回值:0,成功;1,失败
- */
- u8 MPU_Set_Gyro_Fsr(u8 fsr)
- {
- return MPU_Write_Byte(MPU_GYRO_CFG_REG,fsr<<3);
- }
- /**
- * 功能:设置加速度传感器满量程范围
- * 入口参数:fsr,0,+-2g
- * 1,+-4g
- * 2,+-8g
- * 3,+-16g
- * 返回值:0,成功;1,失败
- */
- u8 MPU_Set_Accel_Fsr(u8 fsr)
- {
- return MPU_Write_Byte(MPU_ACCEL_CFG_REG,fsr<<3);
- }
- /**
- * 功能:设置数字低通滤波器
- * 入口参数:lpf,低通滤波器频率(Hz)
- * 返回值:0,成功;1,失败
- */
- u8 MPU_Set_LPF(u16 lpf)
- {
- u8 data=0;
- if(lpf>=188)data=1;
- else if(lpf>=98)data=2;
- else if(lpf>=42)data=3;
- else if(lpf>=20)data=4;
- else if(lpf>=10)data=5;
- else data=6;
- return MPU_Write_Byte(MPU_CFG_REG,data);
- }
- /**
- * 功能:设置采样率(Fs=1KHz)
- * 入口参数:rate=[4,1000]Hz
- * 返回值:0,设置成功;1,设置失败
- */
- u8 MPU_Set_Rate(u16 rate)
- {
- u8 data;
- if(rate>1000)rate=1000;
- if(rate<4)rate=4;
- data=1000/rate-1;
- data=MPU_Write_Byte(MPU_SAMPLE_RATE_REG,data);
- return MPU_Set_LPF(rate/2);
- }
|