【问题标题】:How to delay getOutputStream().write() in Android Studio?如何在 Android Studio 中延迟 getOutputStream().write()?
【发布时间】:2020-03-23 17:35:53
【问题描述】:

我正在使用蓝牙插座将信息从我的手机发送到 Arduino。问题是btSocket.getOutputStream().write(bytes); 发送信息太快,Arduino 无法赶上清空和溢出。在我的 Arduino 上运行的代码减慢了 Arduino 从手机接收信息的能力,并且接收 Arduino 缓冲区溢出(传入数据被窃听,因为缓冲区清空比填充慢得多)。因此,一个解决方案是减慢手机发送信息的速度。

这是我用来从手机向 Arduino 发送信息的功能:

public void send_string_to_lim(String s) {
    if (btSocket != null) {
        try {
            byte[] bytes = s.getBytes();
            btSocket.getOutputStream().write(bytes);
        } catch (IOException e) {
            quick_toast("Error: " + e.toString());
        }
    }
}

这就是 btSocket 的创建方式:(不确定问题是否需要)

if (btSocket == null || !isBtConnected) {
    myBluetooth = BluetoothAdapter.getDefaultAdapter(); //get the mobile bluetooth device
    BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address); //connects to the device's address and checks if it's available
    btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID); //create a RFCOMM (SPP) connection
    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
    btSocket.connect(); //start connection
}

如何减慢btSocket.getOutputStream().write(bytes); 的速度,使其发送信息的速度变慢?添加某种类型的延迟,这样 Arduino 就不会溢出。

【问题讨论】:

    标签: java android android-studio arduino overflow


    【解决方案1】:

    您向 OutputStream 发送一个字节数组,但您也可以一次发送一个字节 - 只需循环遍历您的字节数组,并在发送每个字节后延迟一点。

    我为此使用了 AsyncTask,但由于它已被弃用,您可能希望使用 Threads 或类似的东西来不锁定您的 UI 线程。

    一旦你有一个 AsyncTask 框架或线程,你的工作代码(在 doInBackground 或你的工作函数中)应该是这样的:

    for (int i=0; i<bytes.length();i++)
    {
        btSocket.getOutputStream().write(bytes[i]);
        Thread.sleep(2); //2 ms delay
    }
    

    有一些我没有处理的异常,但如果你愿意,你可以把它放在一个 try-catch 块中。

    AsyncTask 的示例模板(同样由您选择)在这里:https://stackoverflow.com/a/9671602/3550337。我之所以提出它,是因为这是我使用过的并且对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2013-03-30
      • 1970-01-01
      相关资源
      最近更新 更多