4

我正在尝试从我的 Nexus 7 向连接的 USB HID 设备发送十六进制数据,但 Android SDK 方法只能使用 byte[] 缓冲区。

如何使用 bulkTransfer 或 controlTransfer 发送源自十进制字符串值的十六进制数据?

message[0]= 0;
message[1]= 166;
message[2]= 2;
message[3]= 252;
message[4]= 255;

SDK方法:

bulkTransfer(UsbEndpoint endpoint, byte[] buffer, int length, int timeout)

controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)

像这样: http ://pure-basic.narod.ru/article/pickit2.html ,该设备的 PC 应用程序运行良好。

OutBuffer(0)=0
OutBuffer(1)=$A6 ; EXECUTE_SCRIPT
OutBuffer(2)=2
OutBuffer(3)=$FC ; _VDD_GND_OFF
OutBuffer(4)=$FF ; _VDD_ON

更新 - 答案

private void sendData() {
  //byte b = (byte) 129; // (byte) 0x81 Also work
  int status = connection.bulkTransfer(endPointWrite, toByte(129), 1, 250);
}

private static byte toByte(int c) {
  return (byte) (c <= 0x7f ? c : ((c % 0x80) - 0x80));
}

// for received data from USB HID device
private static int toInt(byte b) {
  return (int) b & 0xFF;
}

我在 Google play 上的应用程序 - USB HID TERMINAL

4

1 回答 1

1

This depends on what the target of the message buffer will be.

Since you are getting decimal values from a String you can use the Integer.parseInt method with a radix of 10, then cast to a byte:

byte message[] = new byte[] { (byte)java.lang.Integer.parseInt("0", 10),
            (byte)java.lang.Integer.parseInt("166", 10),
            (byte)java.lang.Integer.parseInt("2", 10),
            (byte)java.lang.Integer.parseInt("252", 10),
            (byte)java.lang.Integer.parseInt("255", 10)
};

If you simply want to send the data over the bulk pipe then you would send it as follows:

bulkTransfer(outEndpoint, message, message.length, 1000);

Control requests typically target some function on the USB device itself and is vendor defined. If you need to send the buffer as a control request you would send it as follows:

controlTransfer(USB_DIR_OUT, VENDOR_DEFINED_REQUEST, VENDOR_DEFINED_VALUE, USB_INTERFACE_INDEX, message, message.length, 1000);
于 2013-08-15T05:32:05.897 回答