Arduino无法正确发送整数 [英] Arduino not sending integers properly
问题描述
我正在尝试从Arduino Uno向Android设备发送整数0到10.但是,Arduino不会单独发送整数,而是将其作为群集发送(有时一次发送2个).我希望能够每5毫秒发送一个整数,并且不延迟任何时间.有什么想法吗?
I am trying to send integers 0 through 10 from my Arduino Uno to my Android device. However, the Arduino is not sending the integers separately, but rather it is sending it as a cluster (sometimes 2 at a time). I want to be able to send an integer every 5 milliseconds and not delay any longer than that. Any ideas?
Arduino代码:
Arduino code:
#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代码:
Android code:
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/控制台输出:
Android Monitor/Console output:
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
推荐答案
似乎串行通信正在作为流(而不是数据报)工作,并且没有保留任何数据边界.
It seems that the serial communication is working as stream (not datagram) and isn't keeping any data boundary.
因此,似乎您应该在发送数据中添加数据分隔符(例如:换行符),并在接收方中对其进行处理(例如:使用BufferedReader
)以保持数据边界.
Therefore, it seems you should add data separator (for example: newline) to your sending data and process it in the receiver (for example: use BufferedReader
) to keep the data boundary.
这篇关于Arduino无法正确发送整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!