gpt4 book ai didi

android - 计数器在线程中运行,由 Arduino 信号驱动,跳过前几个数字

转载 作者:行者123 更新时间:2023-11-29 23:05:56 26 4
gpt4 key购买 nike

我已经在 Arduino(HC-05 蓝牙模块)和我的 Android 应用程序之间建立了蓝牙连接。

每次 Arduino 发送信号(信号只是数字 72)时,我的 Android 应用程序都会读取该信号(作为 InputStream 中的字节)并将“计数器”变量设置为 计数器 = 计数器 - 1

我创建了一个执行此操作的线程。

问题是:

例如,如果我将计数器设置为 30 并启动线程,则 30 的前 3-4 次减法以毫秒为单位发生(它们不与 Arduino 信号同步)。但从 26 日起,一切都完美同步并按预期工作。

我尝试了不同的 Thread.sleep() 次。更长的 sleep 时间使问题变得更糟(更多的减法在毫秒内发生)。 sleep 时间越短越好,但仍然不能解决我的问题。

为什么前 3-6 个减法线程不同步而其他所有减法线程同步?

一些(也许)有用的信息:

有 4 个按钮。 “连接”、“断开连接”、“开始”和“停止”。

  1. “连接”:通过 BluetoothSocket 与 HC-05 建立连接。
  2. “断开连接”:关闭此连接。
  3. “Start”:启动监听来自 HC-05 的 InputStream 数据的线程。
  4. “停止”:停止这个话题。

我的代码(线程代码)。如果有人需要代码的任何其他部分,请提出要求:

//CONNECT
arduinoSocket?.connect()
Toast.makeText(this, "Επιχειρείται σύνδεση με τον Mετρητή...", Toast.LENGTH_LONG).show()
if (!arduinoSocket!!.isConnected) {
startbutton.isEnabled = false
stopbutton.isEnabled = false
Toast.makeText(this, "Σύνδεση απέτυχε.", Toast.LENGTH_SHORT).show()

}
else {
val t = Thread(Runnable {
while(t_control == 1) {
if (arduinoSocket.inputStream.read() == 72) {
counter -= 1
runOnUiThread {
ant_met.text = counter.toString()

}
}
}
Thread.sleep(50)
})

最佳答案

我认为问题出在 Arduino 方面。我相信在 Arduino 端也有一个 OutputStream 类型的设置。根据我的经验,在使用 Arduino 编码时,我必须保留一个用作 OutputStream 的缓冲区。建立连接时,Arduino 端的缓冲区会填满一些存储在缓冲区中的脉冲。建立连接后,Arduino 端缓冲区会立即发送缓冲区中存储的所有元素,因此您会在几毫秒内收到前 3-6 个信号。

这可以很容易地在任何一方使用一些变通办法来避免。 Arduino 可能会在建立连接后清除缓冲区中存储的数据。

如果您不想更改 Arduino 端代码,请在您的 Android 端执行类似的操作。只需读取初始 InputStream 中的所有元素,一段时间后,当 Arduino 中的初始缓冲区被清除时,启动您的原始 Thread

// Clear the initial buffer
val t_init_control = 1
val t = Thread(Runnable {
while(t_init_control == 1) {
arduinoSocket.inputStream.read()
}
})

Timer().schedule(object : TimerTask() {
override fun run() {
// Stop the init thread
t_init_control = 0
startNewThreadHere()
}
}, 2000)

// This is the original thread where you want to keep the track of the pulse from Arduino
fun startNewThreadHere() {
val t = Thread(Runnable {
while(t_control == 1) {
if (arduinoSocket.inputStream.read() == 72) {
counter -= 1
runOnUiThread {
ant_met.text = counter.toString()

}
}
}
})
}

这只是一个解释这个想法的伪代码。希望对您有所帮助!

更新

下面是后来解决问题的方法。我是从这个答案的评论部分引用的。

I sent a Boolean to Arduino in order to determine when to start sending packets of data. In that way, Arduino starts sending data right after opening the InputStream in Android. Hence, there is no flood of "non-transmitted" bytes.

关于android - 计数器在线程中运行,由 Arduino 信号驱动,跳过前几个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56566529/

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