从Android向Arduino发送连续蓝牙流
我正在做一个简单的车辆项目,由Arduino Uno制作,由Android应用程序控制 我的任务是将应用程序中的连续数据流发送到Arduino上的蓝牙模块(HC-06)。 我用onTouch事件和从我的主要活动中调用的新线程完成了这项工作,但显然有些问题,因为应用程序似乎按照我希望的方式发送每个命令,但Arduino会等到手指离开按钮,一次接收所有数据(从action.down到action.up) 了解: 每次命令按钮按下action.down或action_move时,我都会更新一个类似“1255090”的小字符串,将其转换为字节并通过蓝牙发送。 如果我短时间单击按钮,Arduino将收到正确的字符串“1255090”,但如果我将手指保持在按钮上,Arduino将等待字符串,当我松开按钮时,Arduino将收到例如“125509012540901253090125209012510901252090”(取决于我单击的时间) Android活动(部分) 线从Android向Arduino发送连续蓝牙流,android,bluetooth,arduino,outputstream,arduino-uno,Android,Bluetooth,Arduino,Outputstream,Arduino Uno,我正在做一个简单的车辆项目,由Arduino Uno制作,由Android应用程序控制 我的任务是将应用程序中的连续数据流发送到Arduino上的蓝牙模块(HC-06)。 我用onTouch事件和从我的主要活动中调用的新线程完成了这项工作,但显然有些问题,因为应用程序似乎按照我希望的方式发送每个命令,但Arduino会等到手指离开按钮,一次接收所有数据(从action.down到action.up) 了解: 每次命令按钮按下action.down或action_move时,我都会更新一个类似“1
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");
}
}
}
阿杜伊诺环路
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);
}
如果我理解正确,您可以使用多个状态轻松处理它。 例如 State1:123456:用于水龙头, 状态2:123457:用于按住, 状态3:123458:正在发布 等等。 在用户界面中,可以检测用户是点击还是按住 如果按住,则指示arduino执行某些操作,直到收到释放 通过这种方式,您甚至可以在不连续发送bit的情况下处理此情况,并且根据我的理解,您不需要此 如果我错了,请纠正我
谢谢 实际上,按住按钮很重要,因为只要保持,它就会缓慢地增加速度(例如),而松开按钮会缓慢地降低速度。但是,尽管Android控制台显示在按住按钮时字节被正确发送,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);
}