QT使用hidapi库实现USB HID设备读写,读数正常,写入操作时,调用hid_write()函数操作无反应,代码如下:
void WidgetUSB::sendUSBData(unsigned char *data)
{
if (handle)
{
qDebug()<<"发送数据"<<data[0]<<data[1];
hid_write(handle, data, DATA_LENGTH);
}
}
void WidgetControl::sendCommand(uint8_t cmd)
{
unsigned char data_to_send[50];
uchar _cnt = 0;
data_to_send[_cnt++] = 0x12; /*命令*/
data_to_send[_cnt++] = 0x00;
data_to_send[_cnt++] = 0x00;
data_to_send[_cnt++] = 0x00;
ui->widgetUSB->sendUSBData(data_to_send);
}
指令发送到设备,设备没有反应。使USB调试助手,指令是有效的,所以还是代码有问题,hid_write()未使用正确。查看,hidapi.h,果然使用有注意的地方
int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);
/** @brief Write an Output report to a HID device.
The first byte of @p data[] must contain the Report ID. For
devices which only support a single report, this must be set
to 0x0. The remaining bytes contain the report data. Since
the Report ID is mandatory, calls to hid_write() will always
contain one more byte than the report contains. For example,
if a hid report is 16 bytes long, 17 bytes must be passed to
hid_write(), the Report ID (or 0x0, for devices with a
single report), followed by the report data (16 bytes). In
this example, the length passed in would be 17.
hid_write() will send the data on the first OUT endpoint, if
one exists. If it does not, it will send the data through
the Control Endpoint (Endpoint 0).
@ingroup API
@param device A device handle returned from hid_open().
@param data The data to send, including the report number as
the first byte.
@param length The length in bytes of the data to send.
@returns
This function returns the actual number of bytes written and
-1 on error.
*/
第一个字节必须包含 Report ID, 对于支持单报文的设备,这个字节设置为0,剩下的字节包含数据,所以更改代码如下:
void WidgetControl::sendCommand(uint8_t cmd)
{
unsigned char data_to_send[50];
uchar _cnt = 0;
data_to_send[_cnt++] = 0x00; /*必须包含*/
data_to_send[_cnt++] = 0x12; /*命令 */
data_to_send[_cnt++] = 0x00;
data_to_send[_cnt++] = 0x00;
data_to_send[_cnt++] = 0x00;
ui->widgetUSB->sendUSBData(data_to_send);
}
void WidgetUSB::sendUSBData(unsigned char *data)
{
if (handle)
{
qDebug()<<"发送数据"<<data[0]<<data[1];
hid_write(handle, data, DATA_LENGTH+1);
}
}
具体原理不懂,数据发送正常了。