【问题标题】:Arduino not sending integers properlyArduino没有正确发送整数
【发布时间】:2017-08-18 06:39:30
【问题描述】:

我正在尝试将整数 0 到 10 从我的 Arduino Uno 发送到我的 Android 设备。然而,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;
       }
    }   
 }

安卓代码:

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 监视器/控制台输出:

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

【问题讨论】:

  • 您的 Android 代码中的 mmInStream 是什么?
  • mmInStream 是arduino和安卓手机之间蓝牙socket的输入流。

标签: java android bluetooth arduino


【解决方案1】:

似乎串行通信作为流(而不是数据报)工作并且没有保持任何数据边界。

因此,您似乎应该在发送数据中添加数据分隔符(例如:换行符)并在接收器中对其进行处理(例如:使用BufferedReader)以保持数据边界。

【讨论】:

  • 好的,我会试试的。谢谢!
  • @Sam.C 你让我看看这个,这个答案是正确的。 GL 你的项目!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多