问题
I worked this code to receive a single letter of the arduino I can not see any response on the phone text viewer when I want arduino sends the letter 'A' shows me the word 'ON'and if Send 'Z' shows me the word in the text viewer off
Note that the connection between the Android phone arduino been successfully and Android phone sends to arduino but it did not receive
class Ahmed extends Thread {
public void run() {
for (; ; ) {
try {
int bytesAvailable = btSocket.getInputStream().available();
byte []packetBytes= new byte[bytesAvailable];
if (bytesAvailable > 0) {
tb.setText(bytesAvailable+ "ok");
btSocket.getInputStream().read(packetBytes);
for(int i=0; i<bytesAvailable;i++)
{
if (packetBytes[i]==65)
tb.setText("ON");
else if (packetBytes[i] ==90)
tb.setText("off");
}
}
} catch (Exception e) {
}
}
}
}
arduino code
#include<SoftwareSerial.h>
void setup() {
Serial3.begin(9600);
pinMode(13,OUTPUT);
digitalWrite(13,LOW);
}
void loop() {
char x=Serial3.read();
if(x=='A')
{
digitalWrite(13,HIGH);
Serial3.print('A');
}
if(x=='Z')
{digitalWrite(13,LOW);
Serial3.print('Z');
}
}
回答1:
you are updating textview from a thread, it must be throwing some exception but as you have not printed anything in your catch block you are not getting any output or error or anything, always remember, you cannot update views from any thread other than UI thread.
try {
int bytesAvailable = btSocket.getInputStream().available();
byte []packetBytes= new byte[bytesAvailable];
if (bytesAvailable > 0) {
tb.setText(bytesAvailable+ "ok");
btSocket.getInputStream().read(packetBytes);
for(int i=0; i<bytesAvailable;i++)
{
if (packetBytes[i]==65)
tb.setText("ON");
else if (packetBytes[i] ==90)
tb.setText("off");
}
}
} catch (Exception e) {
// ADD THIS TO SEE ANY ERROR
e.printStackTrace();
}
if you are running this thread inside activity class then you can run this
runOnUiThread(new Runnable() {
@Override
public void run() {
tb.setText("ON")
}
});
else you have to implement some mechanism using broadcast receiver or interface for passing the data to your activity/fragment for updating the textview inside runOnUiThread.
来源:https://stackoverflow.com/questions/39723075/receive-character-using-android-phone-from-arduino