本代碼基于正點原子MPU6050六軸傳感器實驗,主控為stm32f103c8t6最小系統板,與匿名科創v4.34上位機進行通訊,可以實時顯示數據波形和飛控狀態。
單片機源程序如下:
- #include "led.h"
- #include "delay.h"
- #include "key.h"
- #include "sys.h"
- #include "lcd.h"
- #include "usart.h"
- #include "mpu6050.h"
- #include "usmart.h"
- #include "inv_mpu.h"
- #include "inv_mpu_dmp_motion_driver.h"
-
- ////串口1發送1個字符
- //c:要發送的字符
- void usart1_send_char(u8 c)
- {
- while(USART_GetFlagStatus(USART1,USART_FLAG_TC)==RESET); //循環發送,直到發送完畢
- USART_SendData(USART1,c);
- }
- //傳送數據給匿名四軸上位機軟件(V2.6版本)
- //fun:功能字. 0XA0~0XAF
- //data:數據緩存區,最多28字節!!
- //len:data區有效數據個數
- void usart1_niming_report(u8 fun,u8*data,u8 len)//匿名上位機協議
- {
- u8 send_buf[32];
- u8 i;
- if(len>28)return; //最多28字節數據
- send_buf[len+4]=0; //校驗數置零
- send_buf[0]=0XAA; //幀頭
- send_buf[1]=0XAA; //幀頭
- send_buf[2]=fun; //功能字
- send_buf[3]=len; //數據長度
- for(i=0;i<len;i++)send_buf[4+i]=data[i]; //復制數據
- for(i=0;i<len+4;i++)send_buf[len+4]+=send_buf[i]; //計算校驗和
- for(i=0;i<len+5;i++)usart1_send_char(send_buf[i]); //發送數據到串口1
- }
- //發送加速度傳感器數據和陀螺儀數據
- //aacx,aacy,aacz:x,y,z三個方向上面的加速度值
- //gyrox,gyroy,gyroz:x,y,z三個方向上面的陀螺儀值
- void mpu6050_send_data(short aacx,short aacy,short aacz,short gyrox,short gyroy,short gyroz)
- {
- u8 tbuf[12];
- tbuf[0]=(aacx>>8)&0XFF;
- tbuf[1]=aacx&0XFF;
- tbuf[2]=(aacy>>8)&0XFF;
- tbuf[3]=aacy&0XFF;
- tbuf[4]=(aacz>>8)&0XFF;
- tbuf[5]=aacz&0XFF;
- tbuf[6]=(gyrox>>8)&0XFF;
- tbuf[7]=gyrox&0XFF;
- tbuf[8]=(gyroy>>8)&0XFF;
- tbuf[9]=gyroy&0XFF;
- tbuf[10]=(gyroz>>8)&0XFF;
- tbuf[11]=gyroz&0XFF;
- usart1_niming_report(0X02,tbuf,12);//飛機傳感器數據,0X02
- }
- //roll:橫滾角.單位0.01度。 -18000 -> 18000 對應 -180.00 -> 180.00度
- //pitch:俯仰角.單位 0.01度。-9000 - 9000 對應 -90.00 -> 90.00 度
- //yaw:航向角.單位為0.1度 0 -> 3600 對應 0 -> 360.0度
- void usart1_report_imu(short roll,short pitch,short yaw)
- {
- u8 tbuf[28];
- u8 i;
- for(i=0;i<28;i++)tbuf[i]=0;//清0
- tbuf[0]=(roll>>8)&0XFF;
- tbuf[1]=roll&0XFF;
- tbuf[2]=(pitch>>8)&0XFF;
- tbuf[3]=pitch&0XFF;
- tbuf[4]=(yaw>>8)&0XFF;
- tbuf[5]=yaw&0XFF;
- usart1_niming_report(0X01,tbuf,28);//飛機姿態等基本信息,0X01
- }
-
- int main(void)
- {
- u8 report=1; //默認開啟上報
- float pitch,roll,yaw; //歐拉角
- short aacx,aacy,aacz; //加速度傳感器原始數據
- short gyrox,gyroy,gyroz; //陀螺儀原始數據
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //設置NVIC中斷分組2:2位搶占優先級,2位響應優先級
- uart_init(500000); //串口初始化為500000
- delay_init(); //延時初始化
- usmart_dev.init(72); //初始化USMART
- LED_Init(); //初始化與LED連接的硬件接口
- KEY_Init(); //初始化按鍵
- MPU_Init(); //初始化MPU6050
- mpu_dmp_init();
-
-
- while(1)
- {
-
- if(mpu_dmp_get_data(&pitch,&roll,&yaw)==0)
- {
- LED0=0;
- MPU_Get_Accelerometer(&aacx,&aacy,&aacz); //得到加速度傳感器數據
- MPU_Get_Gyroscope(&gyrox,&gyroy,&gyroz); //得到陀螺儀數據
- if(report)mpu6050_send_data(aacx,aacy,aacz,gyrox,gyroy,gyroz);//用自定義幀發送加速度和陀螺儀原始數據
- if(report)usart1_report_imu((int)-(roll*100),(int)(pitch*100),(int)-(yaw*100));//左右
- }
- }
- }
復制代碼
全部資料51hei下載地址:
c8t6+mpu6050與上位機通訊.7z
(268.01 KB, 下載次數: 226)
2020-8-10 13:32 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
|