android - 使用 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_�~�
解决方案
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
推荐阅读
- python - 带有循环和条件语句的 Python 脚本
- javascript - 套接字客户端未连接
- excel - 不要在空单元格上运行的公式中显示#N/A
- python - 将 3 个数据框列合并为 1 个优先级,同时避免应用
- reactjs - 我想将状态值传递给 compontDidmount
- docker - Docker .NET Core 映像构建适用于一台主机,但不适用于另一台主机
- c# - 更改材质后再次加载原始纹理(.mtl)
- google-sheets - 在兄弟列中找到迄今为止最后一个非空单元格
- python - 将用户输入转换为十六进制,加入 NULL?
- ruby-on-rails - Stimulus JS,单击背景后模态不会关闭