最近用arduino做一个小玩具,涉及到了蓝牙,安卓端的蓝牙代码我已经写好,可是遇到了些问题:蓝牙数据分段!比如我要接收一组完整的数据“1234567”,由于分段导致数据分成“123”,“45”,“67”三段发过来了(有些时候分成2段,这个不确定)。然后为了解决这个问题,网上找了一些方法,比如线程sleep,但是这样做不符合我的预期,所以pass掉了。我就想着自己定义一个数据包,可是以前重来没有做过,自己鼓捣了一天,一点眉目没有。
下面是我写的获取加速度传感器数据的代码:
[mw_shl_code=c,true]#include
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 initBuffer() {
for (int i=0;i < 5;i++ ) {
accelBuffer= 0x01;
}
accelBuffer[0] = 0xfe;
accelBuffer[4] = 0xff;
}
void loop() {
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;
//Serial.print(0x00);
//Serial.print(a[0],HEX);Serial.print(" ");
//Serial.print(a[1],HEX);Serial.print(" ");
//Serial.print(a[2],HEX);Serial.print(" ");
//Serial.print(0xff);
//Serial.write((char*)accelBuffer);
BTserial.write((char *)accelBuffer);
break;
}
}
}
}
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;
}
}
}
[/mw_shl_code]
float a[3]中分别是xyz三个轴的加速度值(比如分别为“-0.45”,“0.67”,“-0.98”),我现在想把这个三个值加上包头包尾弄成一个数据包,用accelBuffer来存。我想请教各位大神,怎么把三个轴的加速度值装入accelBuffer,让后用serial.write()传数据呢?能不能帮我补全一下我这个代码啊?这个float转byte我没有弄明白。。。。该怎么转呢?
ps:我都把我自己蠢哭了。。。。。。