最近写一个计步器,安卓上的蓝牙代码都写好了,但是遇到一个问题就是蓝牙数据分段,一句话就是一次接收到的数据不完整,然后我就想自己定义一个数据包,可是加速度模块产生的三轴数据有可能是正数或者负数,比如一组三轴数据可能为{-1.56,0.98,-1.23} 或者{1.22,0.56,-10.23},我现在就想请教各位前辈,怎么自己组织数据包,让后把数据用Serial.wirte()字节流的方式发送到手机端,在手机端对数据进行解析?
SoftwareSerial BTserial(2,3);//模拟串口 2-tx 3-rx
unsigned char Re_buf[11],counter=0;
unsigned char sign=0;
float a[3],w[3],angle[3],T;//分别是加速度,角速度,角度,温度
float res ;
byte accelBuffer[5];
void setup() {
Serial.begin(9600);//每隔50ms就从mpu6050模块读取一帧数据(加速度,角速度,角度,温度)
BTserial.begin(9600);
initBuffer();
}
void loop() {
translate();
}
void serialEvent() {//当串口缓冲区有数据时,才运行此函数。当启用该事件时,其实是在两次loop()循环之间检测串口缓冲区中是否有数据,如果有则调用此函数。
while (Serial.available()) {
//char inChar = (char)Serial.read(); Serial.print(inChar); //输出原始数据Output Original Data, use this code
Re_buf[counter]=(unsigned char)Serial.read();
if(counter==0 && Re_buf[0]!=0x55) return; //第 0 号数据不是帧头,跳过�
counter++;
if(counter==11) ///接收到 11 个数据�
{
counter=0; //重新赋值,准备下一帧数据的接收
sign=1;
}
}
}
void translate() {
if(sign)
{
sign=0;
if(Re_buf[0]==0x55) //包头�
{
switch(Re_buf [1])
{
case 0x51:
a[0] = (short(Re_buf [3]<<8| Re_buf [2]))/32768.0*16;
a[1] = (short(Re_buf [5]<<8| Re_buf [4]))/32768.0*16;
a[2] = (short(Re_buf [7]<<8| Re_buf [6]))/32768.0*16;
T = (short(Re_buf [9]<<8| Re_buf [8]))/340.0+36.25;
break;
case 0x52:
w[0] = (short(Re_buf [3]<<8| Re_buf [2]))/32768.0*2000;
w[1] = (short(Re_buf [5]<<8| Re_buf [4]))/32768.0*2000;
w[2] = (short(Re_buf [7]<<8| Re_buf [6]))/32768.0*2000;
T = (short(Re_buf [9]<<8| Re_buf [8]))/340.0+36.25;
break;
case 0x53:
angle[0] = (short(Re_buf [3]<<8| Re_buf [2]))/32768.0*180;
angle[1] = (short(Re_buf [5]<<8| Re_buf [4]))/32768.0*180;
angle[2] = (short(Re_buf [7]<<8| Re_buf [6]))/32768.0*180;
T = (short(Re_buf [9]<<8| Re_buf [8]))/340.0+36.25;
res = sqrt(sq(a[0]) + sq(a[1]) + sq(a[1]));
//BTserial.print(res);
//Serial.println(res);
initBuffer();
for (int j =1;j < 4;j++) {
accelBuffer[j] = (char)a[j-1];
//Serial.println(a[j-1]);
}
for (int j =0;j < 5;j++) {
//Serial.println(accelBuffer[j]);
}
//Serial.write((char*)accelBuffer);
BTserial.write((char *)accelBuffer);
break;
}
}
}
}
void initBuffer() {
for (int i=0;i < 5;i++ ) {
accelBuffer[i] = 50 ;
}
accelBuffer[0] = 0xfe;
accelBuffer[4] = 0xff;
}
上面是我写的代码,但是感觉有问题,昨天才接触这个,好多问题都想不明白。请前辈们指教!