全部在标题中。当我从Arduino向Android发送String数据时,会收到此���������������� 我竭尽全力获得真正的价值,但一无所获。请帮忙。编辑 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_�~�
答案 0 :(得分:0)
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
关于传输层问题(废话数据): 这可能是由于波特率设置不正确造成的; read this和this(据我了解,115200可能有效!)