基于arduino的串口通信学习

一、串口通信格式

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;}

}}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容