【问题标题】:Sending a simple USB BulkTransfer and receiving a response发送简单的 USB BulkTransfer 并接收响应
【发布时间】:2020-03-05 14:48:25
【问题描述】:

我正在尝试通过 USB 从一组称重秤中获取重量值。这应该很简单,根据他们的文档,我需要发送两个字节,字母“W”和回车字节。然后它以 16 字节的数据作为响应,表示设备上的当前重量。

设备有 1 个接口,2 个端点,最大数据包大小为 64。我相信我必须使用bulkTransfer 函数,因为端点类型是 USB_ENDPOINT_XFER_BULK。

这是文档图形:

我应该如何发送此请求并接收响应?我的尝试如下,响应只是一个Start of Heading 符号,然后是一个反引号符号“`”和一个零负载。我尝试在轮询循环或单个请求上运行代码,但得到相同的结果。

    val connection = usbManager.openDevice(scales)
    val intf: UsbInterface = scales.getInterface(0)
    connection.claimInterface(intf, true)

    val endpointReadIn = intf.getEndpoint(0)
    val endpointWriteOut = intf.getEndpoint(1)

    val bytes = byteArrayOf(0x57.toByte(), 0x0D.toByte())

    thread {
        val request = connection.bulkTransfer(endpointWriteOut, bytes, bytes.size, 0)
        Log.d(TAG, "Was request to write successful? $request")
        val buffer = ByteArray(16)
        val response = connection.bulkTransfer(endpointReadIn, buffer, buffer.size, 0)
        Log.d(TAG, "Was response from read successful? $response")
        val responseString = StringBuilder()
        for (i in 0..15) {
            responseString.append(buffer[i])
        }
        Log.d(TAG, "Response: $responseString")

        val hex = toHexString(buffer)
        Log.d(TAG, "Hex: $hex")

        connection.close()
    }


    fun fromHexString(hexString: String): ByteArray {
        val len = hexString.length / 2
        val bytes = ByteArray(len)
        for (i in 0 until len) bytes[i] = hexString.substring(2 * i, 2 * i + 2).toInt(16).toByte()
        return bytes
    }

输出:

Was request to write successful? 2
Was response from read successful? 2
Response: 19600000000000000
Hex:  01 60 00 00 00 00 00 00 00 00 00 00 00 00 00 00

【问题讨论】:

    标签: android usb android-usb


    【解决方案1】:

    这里有一些缺失的部分。我认为最重要的是没有指定波特率、数据位、停止位和奇偶校验,这些都是通过controlTransfer 函数实现的。

    尽管在设置这些时获得了成功的响应,但我最终还是无法让它自己工作。然后我发现了这个lovely library,它与这个 RS232 设备兼容,并且运行良好。我只需要指定 vid / pid 即可使用 FtdiSerialDriver 类获取自定义驱动程序。

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 2013-08-06
      相关资源
      最近更新 更多