一、串口通信格式
START (起始位) D0~D7(数据位)P(校验位) STOP(停止位)
二、串口通信步骤
1、配置波特率 serial[x].begin(speed);
2、查看串口缓冲中是否有数据(输出可忽略) serial[x].available(); //有效数据
serial[x].read(); //读取数据
3、读取或写入串行数据 serial[x].print(data);
三、程序范例
unsigned char Re_buf[11],counter=0;//定义数组储存数据
unsigned char sign=0;
float a[3],w[3],angle[3],T;
void setup() {Serial.begin(9600);}
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*16;
w[1]=(short(Re_buf[5]<<8|Re_buf[4]))/32768.0*16;
w[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 0x53: //角度
angle[0]=(short(Re_buf[3]<<8|Re_buf[2]))/32768.0*16;
angle[1]=(short(Re_buf[5]<<8|Re_buf[4]))/32768.0*16;
angle[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 0x53:
* angle[0]=(short(Re_buf[3]<<8|Re_buf[2]))/32.8 //Vx
* angle[1]=(short(Re_buf[5]<<8|Re_buf[4]))/32.8 //Vy
* angle[2]=(short(Re_buf[7]<<8|Re_buf[6]))/32.8 //Vz
*/}}}
void serialEvent{
while(Serial.available()){ //CRC循环冗余算法
Re_buf[counter]=(unsigned char)Serial.read();
if(counter==0&&Re_buf[0]!=0x55) return; //if the first data is not the head
counter++;
if(counter==11) //have receive all the data
{counter=0;sign=1;}
}}
网友评论