串口通信的MPU姿態(tài)傳感器數(shù)據(jù)包解析技術
2018/1/19??????點擊:
本程序段描述了MPUXXX姿態(tài)傳感器通過串口發(fā)送給主機時的數(shù)據(jù)包解析過程,僅供參考。
void Analysize_Data()
{
float CurrentTimeCounter = 0;
while (true){
bool data_1_catched = false;//緩存記錄數(shù)據(jù)是否捕獲到
//int CurrentTimeCounter = 0;
int buffer_len = buffer.Count;//獲取buffer長度
while (buffer.Count >= 5)//至少要包含頭(2字節(jié)) +功能字(1字節(jié)) +長度(1字節(jié)) +校驗(1字節(jié))
{
//1 查找數(shù)據(jù)頭
if (buffer[0] == 0x55 && buffer[1] == 0xaa)//檢測是否是包頭
{
int len = buffer[3];//數(shù)據(jù)長度
//數(shù)據(jù)不夠時移除數(shù)據(jù)
if (buffer.Count < len + 5)
{
buffer.RemoveRange(0, buffer.Count - 1);
break;
}
if (buffer[3] == 0x06) //該幀長度16字節(jié)//數(shù)據(jù)位沒有0x06位
{
Ctrl_Roll = (float)(((short)((buffer[4] << 8) | buffer[5])) / 100.0);//解析協(xié)議的,提取數(shù)據(jù)并將16進制轉(zhuǎn)換為10進制,
Ctrl_Pitch = (float)(((short)((buffer[6] << 8) | buffer[7])) / 100.0);
Ctrl_Yaw = (float)(((short)((buffer[8] << 8) | buffer[9])) / 10.0);
data_1_catched = true;
buffer.RemoveRange(0, len + 4);//正確分析一條數(shù)據(jù),從緩存中移除數(shù)據(jù)。數(shù)據(jù)移除
if (data_1_catched)
{
//更新界面
this.Invoke((EventHandler)(delegate//對監(jiān)控的數(shù)據(jù)的實時曲線進行跟新
{
chart1.Series[0].Points.AddXY(CurrentTimeCounter, Ctrl_Roll);
chart1.Series[1].Points.AddXY(CurrentTimeCounter, Ctrl_Pitch);
chart1.Series[2].Points.AddXY(CurrentTimeCounter, Ctrl_Yaw);
}));
}
}
else
{
buffer.RemoveAt(0);
break;
}
}
else
{ //這里是很重要的,如果數(shù)據(jù)開始不是頭,則刪除數(shù)據(jù)
buffer.RemoveAt(0);
}
}
}
}
WONGLOVE將一直關注*實用的編程技術,以饗網(wǎng)友。
- 上一篇:UNITY3D MonoDevelop不能粘貼外部代碼文字怎 2018/3/4
- 下一篇:串口協(xié)議以及串口二進制整數(shù)據(jù)包解析 2018/1/11