首页 > 解决方案 > 使用 HC-05 将字符串从 arduino 发送到 android 时接收垃圾数据

问题描述

一切都在标题中。当我将字符串数据从 Arduino 发送到 android 时,我会收到这个 ������������������。我尽一切努力获得真正的价值,但没有。请帮忙。在这里编辑 Arduino 部分:

#include <SoftwareSerial.h>
#define rxPin 19
#define txPin 18
SoftwareSerial BTserial(rxPin, txPin);

void setup() {
  // put your setup code here, to run once:
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  BTserial.begin(38400);
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  BTserial.println("ROGER AIME LES POMMES. HEIN LE SALAUD");
  delay(5000);
}

Android part :

public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
        while (true) {
            try {
                bytes = mmInStream.read(buffer);//read bytes from input buffer
                bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();
            }

            catch (IOException e) {
                break;
            }
        }
    }

在 onCreate

bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == handlerState) {
                byte[] readBuff = (byte[]) msg.obj;
                String readMessage = new String(readBuff,0,msg.arg1);
                blue_tv2.setText("Data Received = " + readMessage);
                Log.d("", "handleMessage: "+readMessage);
            }
        }
    };

我跑步时的控制台。

D/: handleMessage: z
D/: handleMessage: z_�~�
D/: handleMessage: z
D/: handleMessage: z_�~�
D/: handleMessage: 7
D/: handleMessage: z_�~�
D/: handleMessage: 7
D/: handleMessage: z_�~�

标签: androidbluetootharduinohc-05

解决方案


mminStream.read() 读取并返回一个字节;您永远不会真正将字节读取到缓冲区并且正在解码“全 0 字节”缓冲区;

阅读String构造函数和InputStream

我只会纠正你错的部分,不要碰其他任何东西!

public void run() {
    byte[] buffer = new byte[1024];
    int bytes;//rename this to something else; the name doesn't explain what this variable actually holds and might cause confusion
    String temp_msg="";
    while (true) {
        try {
            bytes = mmInStream.read(buffer);//bytes now holds the number of read bytes which are writen to buffer;
            String readMessage = new String(buffer, 0, bytes);//now this decodes buffer bytes residing in indexes from 0 to bytes value
            //now readmessage holds the message
            //rest of the code

关于传输层问题(无意义的数据):这可能是因为波特率设置错误;阅读这个这个(据我了解,115200 可能有效!)


推荐阅读