【发布时间】:2015-12-15 19:34:45
【问题描述】:
我正在开发一个简单的车辆项目,由 Arduino Uno 制作并由 Android 应用程序控制。
我的事情是从应用程序向我在 Arduino 上的蓝牙模块 (HC-06) 发送连续流。 我用 onTouch 事件和一个从我的主要活动调用的新线程来做到这一点,但显然有问题,因为应用程序似乎按照我想要的方式发送每个命令,但 Arduino 等到手指离开按钮并接收所有数据(从 action.down 到 action.up)。
理解: 每次命令按钮为 action.down 或 action_move 时,我都会更新一个像“1255090”这样的小字符串,将其转换为字节并通过蓝牙发送。 如果我短暂单击按钮,Arduino 将收到正确的字符串“1255090”,但如果我将手指放在按钮上,Arduino 会等待字符串,当我松开按钮时,Arduino 会收到例如“125509012540901253090125209012510901252090”(取决于我点击了多长时间)。
Android 活动(部分)
drive.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent m) {
if (m.getAction() != MotionEvent.ACTION_UP) {
accelerer(); // inscreases the speed
str_flux(); // constructs the string
byte[] bytes = new byte[0];
try { bytes = flux.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
sendReceiveBT.write(bytes); // calls the thread's method
} else{ralentir();}
return true;
}
});
线程
package com.*.vehicle.util;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
public class SendReceiveBytes implements Runnable {
private BluetoothSocket btSocket;
private OutputStream btOutputStream = null;
String TAG = "SendReceiveBytes";
public SendReceiveBytes(BluetoothSocket socket) {
btSocket = socket;
try { btOutputStream = btSocket.getOutputStream(); } catch (IOException streamError) { Log.e(TAG, "Error when getting input or output Stream"); }
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
}
public void write(byte[] bytes) {
try {
btOutputStream.write(bytes); // Send the bytes to Arduino
btOutputStream.flush(); // don't know if it really does something...
Log.e(TAG, "SUCCESS !");
}
catch (IOException e) {
Log.e(TAG, "Error when writing to btOutputStream");
}
}
}
Arduino 循环
void loop() {
s = Serial.readString(); // 1255090
if (s!=""){
Serial.println(s);
bt_direction = s.substring(0,1).toInt();
bt_speed = s.substring(1,4).toInt();
bt_angle = s.substring(4,7).toInt();
s = "";
} else{
if (bt_speed>0){
for(int i=bt_speed;i>=0;i--){bt_speed--;}
}
else{ bt_speed = 0; }
}
if (bt_direction==1){bt_dir = true;} else{bt_dir = false;}
if (bt_speed==0){stop_motor();} else{dc_motor(bt_speed, bt_dir);}
Serial.println(bt_direction);
servo_turn(bt_angle);
}
【问题讨论】:
标签: android bluetooth arduino outputstream arduino-uno