问题描述
我使用此代码来接收 arduino 的单个字母我在电话文本查看器上看不到任何响应,当我希望 arduino 发送字母A"时向我显示ON"字样,如果发送Z"显示我关闭文本查看器中的单词
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
注意安卓手机arduino连接成功,安卓手机发送到arduino但是没有接收
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 代码
#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');
}
}
推荐答案
您正在从一个线程更新 textview,它肯定会抛出一些异常,但由于您没有在 catch 块 中打印任何内容,所以没有得到任何输出或错误或任何东西,永远记住,你不能从 UI 线程以外的任何线程更新视图.
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")
}
});
否则,您必须使用广播接收器或接口实现某种机制,以将数据传递给您的活动/片段以更新内部的textviewrunOnUiThread.
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.
这篇关于使用来自 arduino 的 Android 手机接收角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!