gpt4 book ai didi

Android通过蓝牙发送信息,快速记录

转载 作者:行者123 更新时间:2023-11-29 16:47:09 25 4
gpt4 key购买 nike

我正在尝试编写一个应用程序,通过 BT 将球的坐标传递给 Arduino。坐标每 4 毫秒发送一次。对于此测试,我发送“123”而不是完整坐标。我现在(在 Arduino 串行监视器上)得到的是“123123123123123...”,它仅在我关闭应用程序后刷新。

我想要实现的是每行显示“123”,在消息发送后立即显示。

安卓代码BT:

 private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private OutputStream outStream ;

UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
BluetoothSocket tmp = null;
mmDevice = device;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
tmp = device.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
mmSocket = tmp;
}

public void run() {
// Cancel discovery because it otherwise slows down the connection.
mBluetoothAdapter.cancelDiscovery();

try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect();
Log.i(TAG, "run: CONNECTED");
} catch (IOException connectException) {
Log.i(TAG, "run: NOT CONNECTED");
}
}

// Closes the client socket and causes the thread to finish.
public void cancel() {
try {
mmSocket.close();
if(outStream != null)
outStream.close();
finish();
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
}
}

//Sending Message
public void writeData(String data){
String info = data;
try {
outStream = mmSocket.getOutputStream();
outStream.write(info.getBytes());
Log.i(TAG, "writeData: MSG SENT");
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "run: CANT SEND MSG");
}
}

public boolean isConnected(){
return mmSocket.isConnected();
}
}

在我的主要功能中,我调用:

if(connectThread.isConnected())
connectThread.writeData("123");

Arduino 代码:

String incomingByte;

void setup() {
//pinMode(53, OUTPUT);
Serial.begin(9600);
}

void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.readString();
Serial.println(incomingByte);
delay(10);
}
}

最佳答案

串口通信没有消息的概念,除非你自己弄。

Serial.readString() 用时间分隔您的“消息”(默认情况下为 1 秒),并且您发送的“消息”间隔 4 毫秒。这显然连接了您的“消息”。

要真正发送消息,您需要将它们分隔开。您可以通过发送线路来做到这一点。

在 Android 上,您需要以换行符结束消息:

outStream.write(info.getBytes());
outStream.write(10); // send a new line character (ASCII code 10)

而在 Arduino 上,您需要阅读,直到找到换行符:

incomingByte = Serial.readStringUntil('\n');
Serial.read(); // remove the leftover new line character from the buffer

关于Android通过蓝牙发送信息,快速记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47594415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com