我正在尝试从我的Arduino Uno向我的Android设备发送0到10的整数。但是,Arduino不是单独发送整数,而是将它作为一个集群发送(有时一次发送2个)。我希望能够每5毫秒发送一个整数,并且不会延迟任何时间。有什么想法吗?
Arduino代码:
#include <SoftwareSerial.h>
const int RX_PIN = 8;
const int TX_PIN = 9;
SoftwareSerial bluetooth(RX_PIN, TX_PIN);
char commandChar;
void setup (){
bluetooth.begin (9600);
Serial.begin(9600);
}
void loop () {
if(bluetooth.available()){
commandChar = bluetooth.read();
switch(commandChar){
case '*':
for(int i = 0; i < 11; i++){
bluetooth.print(i);
delay(5);
}
break;
}
}
}
Android代码:
public void run() {
initializeConnection();
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
while (true) {
try {
if(mmSocket!=null) {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
Log.e("Received Message ", readMessage);
}
}
} catch (IOException e) {
Log.e("ERROR ", "reading from btInputStream");
break;
}
}
}
Android Monitor /控制台输出:
08-18 19:46:32.319 6720-6749/? E/Received Message: 0
08-18 19:46:32.324 6720-6749/? E/Received Message: 1
08-18 19:46:32.324 6720-6749/? E/Received Message: 23
08-18 19:46:32.324 6720-6749/? E/Received Message: 4
08-18 19:46:32.379 6720-6749/? E/Received Message: 56
08-18 19:46:32.379 6720-6749/? E/Received Message: 78
08-18 19:46:32.379 6720-6749/? E/Received Message: 91
08-18 19:46:32.384 6720-6749/? E/Received Message: 0
答案 0 :(得分:1)
似乎串行通信正在作为流(而不是数据报)工作,并且不保持任何数据边界。
因此,您似乎应该在发送数据中添加数据分隔符(例如:换行符)并在接收器中处理它(例如:使用BufferedReader
)以保持数据边界。