Android和Arduino都通过蓝牙接收奇怪的值

时间:2012-10-03 23:28:16

标签: android bluetooth arduino communication

我在Android端使用BluetoothChat代码使用聊天框向Arduino UNO发送ON / OFF信号(我发送110,119或其他如下定义的情况),但当我显示收到的值时,它在Arduino串行监视器中显示奇怪的值,即255,254,250或245,并在Android端回复奇怪的值。

但令人惊讶的是,当我从android发送这些命令并且没有其他指令/ LED正确执行/打开/关闭时,只有110,119等中的单个条件成立。

任何人都可以帮我解决问题吗?下面是我的arduino代码。

int data; 
String message; 

void setup () 
{ 
Serial.begin (57600); 

pinMode (6, OUTPUT); 
pinMode (7, OUTPUT); 
pinMode (8, OUTPUT); 
pinMode (9, OUTPUT); 
pinMode (10, OUTPUT); 

digitalWrite(6, LOW); // off LED 1 at pin6 
digitalWrite(7, LOW); // off LED 2 at pin7 
digitalWrite(8, LOW); // off LED 3 at pin8 
digitalWrite(9, LOW); // off LED 4 at pin9 
digitalWrite(10, LOW); // off LED 5 at pin10 
}

void loop () { 
int i=0; 
if (Serial.available()>0) 
{ 
int data= Serial.read(); 

Serial.println (" Received data: "); 
Serial.println (data); 

if (data==110) //q 
{ 
digitalWrite(6, HIGH); // turn on LED 1 at pin6 
message = "LED 1 On"; 
Serial.println (message); 

} 
if (data==102) // a 
{ 
digitalWrite(6, LOW); // off LED 1 at pin6 
message = "LED 1 Off"; 
Serial.println (message); 
} 

if (data==96) //c 
{ 
digitalWrite(7, HIGH); //on LED 2 
message = "LED 2 On"; 
Serial.println (message); 
} 

if (data==115) //d 
{ 
digitalWrite(7, LOW); // off LED 2 
message = "LED 2 Off"; 
Serial.println (message); 
} 

if (data==111) //e 
{ 
digitalWrite(8, HIGH); //on LED 3 
message = "LED 3 On"; 
Serial.println (message); 
} 

if (data==97)// f 
{ 
digitalWrite(8, LOW); //sets the LED 3 
message = "LED 3 Off"; 
Serial.println (message); 
} 

if (data==107) //g 
{ 
digitalWrite(9, HIGH); //turn on LED 4 
message = "LED 4 On"; 
Serial.println (message); 
} 

if (data==120)//h 
{ 
digitalWrite(9, LOW); //sets the LED 4 
message = "LED 4 Off"; 
Serial.println (message); 
} 


if (data==99) //i 
{ 
digitalWrite(10, HIGH); //sets the LED 5 
message = "L5 high"; 
Serial.println (message); 
} 

if (data==104) //j 
{ 
digitalWrite(10, LOW); //sets the LED 5 
message = "LED 5 Off"; 
Serial.println (message); 
} 

if (data==112) //y 
{ 
digitalWrite(6, HIGH); // turn on ALL LEDs 
digitalWrite(7, HIGH); 
digitalWrite(8, HIGH); 
digitalWrite(9, HIGH); 
digitalWrite(10, HIGH); 
message = "ALL LEDs ON"; 
Serial.println (message); 
} 


if (data==122)//z 
{ 
digitalWrite(6, LOW); //Turn off all LEDs 
digitalWrite(7, LOW); 
digitalWrite(8, LOW); 
digitalWrite(9, LOW); 
digitalWrite(10, LOW); 
Serial.println ("ALL LEDs OFF"); 
} 

else 
{ 
digitalWrite(13, HIGH); //sets the LED 5 
delay(3000); //3sec 
digitalWrite(13, LOW); 
delay(3000); 
Serial.println (" else case executed "); 

} ////end of else 

}
data=0;
}

2 个答案:

答案 0 :(得分:1)

尝试 char data = Serial.read();

显示Android的Java代码。

查看Bluetooth Arduino&Android

的100%工作代码

答案 1 :(得分:0)

如果您使用的是Arduino Uno,那么如果您已经使用串口与蓝牙通信,则不能使用串行监视器来打印值,因为它只有一个串口。

您必须使用软件串行库或使用Arduino Mega,它有4个串行端口。