【发布时间】:2016-06-27 08:51:54
【问题描述】:
我想通过蓝牙和 Android 设备进行 Arduino 之间的通信
在 Arduino 中,我正在使用
SoftwareSerial.h
下面是代码
#include <SoftwareSerial.h>
int ledPin1 = 5;
int state = 0;
int flag = 0;
SoftwareSerial mySerial(0, 1);
void setup() {
// put your setup code here, to run once:
pinMode(ledPin1, OUTPUT);
digitalWrite(ledPin1, LOW);
Serial.begin(9600);
mySerial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()>0){
state = Serial.read();
flag = 0;
}
if (mySerial.available()) {
int k = mySerial.read();
mySerial.write(k);
}
}
在 Android 方面,我使用的是BluetoothSPPLibrary
有一个名为 BluetoothService.java 的类
因为有ConnectedThread
public void run()
{
Log.d(TAG, "run: Called");
byte[] buffer;
ArrayList<Integer> arr_byte = new ArrayList<Integer>();
// Keep listening to the InputStream while connected
while (true) {
try {
int data = mmInStream.read();
Log.d(TAG, "run: "+data);
if(data == 0x0A) {
} else if(data == 0x0D) {
buffer = new byte[arr_byte.size()];
for(int i = 0 ; i < arr_byte.size() ; i++) {
buffer[i] = arr_byte.get(i).byteValue();
}
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothState.MESSAGE_READ
, buffer.length, -1, buffer).sendToTarget();
arr_byte = new ArrayList<Integer>();
} else {
arr_byte.add(data);
}
} catch (IOException e) {
connectionLost();
// Start the service over to restart listening mode
BluetoothService.this.start(BluetoothService.this.isAndroid);
break;
}
}
}
但是
int data = mmInStream.read();
这里的数据不是来自上面的代码
【问题讨论】: