【发布时间】:2018-11-02 17:30:55
【问题描述】:
基于 SDK 的蓝牙聊天示例,我正在开发一个在 android 设备和 arduino 之间传输字符串的应用程序。 我有以下问题:
1- 如果我使用此代码,我会丢失 arduino 发送的第一个字节:
// Keep listening to the InputStream while connected
while (true) {
try {
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MESSAGE_READ, bytes,-1, buffer).sendToTarget();
但是这样就可以了:
bytes = mmInStream.available();
if(bytes != 0) {
SystemClock.sleep(100); //pause and wait for rest of data.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
请解释一下?
2- Arduino 在从设备接收到字符串时发送字符串“OK”。 如何在我的应用中将其用作 ACK(nowledgement)?
我试过了,但没有成功:
String ack = ""; //global variable
sendstring("test string");// send a test string to arduino
SystemClock.sleep(100); //wait for arduino response
if(ack.equals("OK")) txtv.setText(" well received"); //well done
在处理程序中:
if(msg.what == Bluetooth.MESSAGE_READ){
String receivedstring = new String((byte[]) msg.obj, 0, msg.arg1);
ack = receivedstring ;
我没有得到 ack = "OK" ,并且 "well received" 没有显示在文本视图中!!
非常感谢您的帮助
【问题讨论】: