arduino 与mpu6050使用tx rx通信如何做到不受延时的影响?
连接好后,使用arduino的tx rx接口与mpu6050进行通信,代码如下,运行正常,但是加上delay(5000);之后,就成一堆乱码了,这是为什么?如何包装成一个api,然后进行随时调用呢?
/*
This code is used for connecting arduino to serial mpu6050 module, and test in arduino uno R3 board.
connect map:
arduino mpu6050 module
VCC 5v/3.3v
TX RX<-0
TX TX->1
GND GND
note:
because arduino download and mpu6050 are using the same serial port, you need to un-connect 6050 module when you want to download program to arduino.
Created 14 Nov 2013
by Zhaowen
serial mpu6050 module can be found in the link below:
http://item.taobao.com/item.htm?id=19785706431
*/
unsigned char Re_buf,counter=0;
unsigned char sign=0;
float a,w,angle,T;
void setup() {
// initialize serial:
Serial.begin(115200);
}
void loop() {
if(sign)
{
sign=0;
if(Re_buf==0x55) //检查帧头
{
switch(Re_buf )
{
case 0x51:
a = (short(Re_buf <<8| Re_buf ))/32768.0*16;
a = (short(Re_buf <<8| Re_buf ))/32768.0*16;
a = (short(Re_buf <<8| Re_buf ))/32768.0*16;
T = (short(Re_buf <<8| Re_buf ))/340.0+36.25;
break;
case 0x52:
w = (short(Re_buf <<8| Re_buf ))/32768.0*2000;
w = (short(Re_buf <<8| Re_buf ))/32768.0*2000;
w = (short(Re_buf <<8| Re_buf ))/32768.0*2000;
T = (short(Re_buf <<8| Re_buf ))/340.0+36.25;
break;
case 0x53:
angle = (short(Re_buf <<8| Re_buf ))/32768.0*180;
angle = (short(Re_buf <<8| Re_buf ))/32768.0*180;
angle = (short(Re_buf <<8| Re_buf ))/32768.0*180;
T = (short(Re_buf <<8| Re_buf ))/340.0+36.25;
Serial.print("a:");
Serial.print(a);Serial.print(" ");
Serial.print(a);Serial.print(" ");
Serial.print(a);Serial.print(" ");
Serial.print("w:");
Serial.print(w);Serial.print(" ");
Serial.print(w);Serial.print(" ");
Serial.print(a);Serial.print(" ");
Serial.print("angle:");
Serial.print(angle);Serial.print(" ");
Serial.print(angle);Serial.print(" ");
Serial.print(angle);Serial.print(" ");
Serial.print("T:");
Serial.println(T);
break;
}
}
}
}
void serialEvent() {
while (Serial.available()) {
//char inChar = (char)Serial.read(); Serial.print(inChar); //Output Original Data, use this code
Re_buf=(unsigned char)Serial.read();
if(counter==0&&Re_buf!=0x55) return; //第0号数据不是帧头
counter++;
if(counter==11) //接收到11个数据
{
counter=0; //重新赋值,准备下一帧数据的接收
sign=1;
}
}
}
本帖最后由 sing1155665 于 2014-10-17 09:24 编辑
你的Delay加在哪里了?
延时可以用中断啊,或者用状态机实现你的逻辑吧。 本帖最后由 Super169 于 2014-10-17 09:43 编辑
這個題目是要讓大家猜猜在那裡加上 delay(5000) 嗎?
應該不會是放在 interrupt 之內吧. {:soso_e149:}
页:
[1]