- unsigned char Re_buf[30],counter=0;
- unsigned char sign=0;
- void serialEvent() {
- while (Serial.available()) {
- Re_buf[counter]=(unsigned char)Serial.read();
- if(counter==0 && Re_buf[0]!=0XAA) return; // 检查帧头
- counter++;
- if(counter==13) //接收到数据
- {
- counter=0; //重新赋值,准备下一帧数据的接收
- sign=1;
- }
- }
- }
- void setup() {
- Serial.begin(19200);
- Serial.write(0XAA);
- Serial.write(0X00);
- Serial.write(0X00);
- Serial.write(0X20);
- Serial.write(0X00);
- Serial.write(0X01);
- Serial.write(0X00);
- Serial.write(0X04);
- Serial.write(0X25);
- }
- void loop()
- {
- if(sign)
- {
- sign=0;
- if(Re_buf[0]==0XAA && Re_buf[1]==0X00 ) //检查帧头,
- {
- Serial.print(Re_buf[0],HEX);
- Serial.print(Re_buf[1],HEX);
- Serial.print(Re_buf[2],HEX);
- Serial.print(Re_buf[3],HEX);
- Serial.print(Re_buf[4],HEX);
- Serial.print(Re_buf[5],HEX);
- Serial.print(Re_buf[6],HEX);
- Serial.print(Re_buf[7],HEX);
- Serial.print(Re_buf[8],HEX);
- Serial.print(Re_buf[9],HEX);
- Serial.print(Re_buf[10],HEX);
- Serial.print(Re_buf[11],HEX);
- Serial.print(Re_buf[12],HEX);
- Serial.print(Re_buf[13],HEX);
- int distance = 0;
- distance = (Re_buf[8]*256+ Re_buf[9]);
- Serial.print(" Distance = ");
- Serial.print(distance);
- Serial.println(" MM");
- }
- }
- }
复制代码 |