一、前言
有关MPU6050模块读取六轴传感器数值的详细内容,详见【STM32+HAL】姿态传感器陀螺仪MPU6050模块
二、所用工具
1、芯片:STM32F103C8T6
2、配置软件:CUBEMX
3、编译器:KEIL5
4、产品型号:GY-25
5、使用芯片:MPU6050
6、商品编码:MK002824
三、实现功能
直接读取并输出俯仰角,横滚角,航偏角数值
四、HAL库配置步骤
1、配置串口一、二,参数一致
2、中断配置
五、KEIL填写代码
1、初始化
#define RXBUFFERSIZE 256uint8_t aRxBuffer;
int flag=0;
int16_t y=0,p=0,r=0;
double YAW=0,PITCH=0,ROLL=0;uint8_t query1 = 0xA5;
uint8_t query2 = 0x51;
uint8_t query3 = 0x55;printf("Hello World!\r\n");HAL_Delay(500);HAL_UART_Transmit_IT(&huart2,&query1,1);HAL_UART_Transmit_IT(&huart2,&query3,1);HAL_UART_Receive_IT(&huart2, (uint8_t *)&aRxBuffer, 1);
2、串口回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{UNUSED(huart);if(huart==&huart2){static uint8_t k=0,rebuf[8]={0};HAL_GPIO_TogglePin(LED_GPIO_Port,LED_Pin);rebuf[k++] = aRxBuffer; //读取接收到的数据if(!(rebuf[0]==0xAA)) //如果帧头错误,清缓存{k=0;rebuf[0]=0;}if(k==8) //数据接收完毕{if(rebuf[7]==0x55) //判断帧尾,正确则解析姿态角{y=(rebuf[1]<<8|rebuf[2]); //y,p,r为真实值的100倍p=(rebuf[3]<<8|rebuf[4]);r=(rebuf[5]<<8|rebuf[6]);flag=1;}k=0;//清缓存}HAL_UART_Receive_IT(&huart2, (uint8_t *)&aRxBuffer, 1);}
}
3、main.c
/* USER CODE BEGIN WHILE */while (1){if(flag==0){HAL_UART_Transmit_IT(&huart2,&query1,1);HAL_UART_Transmit_IT(&huart2,&query2,1);HAL_Delay(10);}else if(flag==1){flag=0;printf("Yaw=%.2f Pitch=%.2f ROLL=%.2f\r\n",(double)y/100.0f,(double)p/100.0f,(double)r/100.0f);
// HAL_Delay(200);}/* USER CODE END WHILE *//* USER CODE BEGIN 3 */}/* USER CODE END 3 */
六、注意事项
1、输出格式
2、命令字节
3、注意事项
七、源码提供
【STM32+HAL】GY25倾斜度角度模块源码