hid编程 qt_QtUSBHID—— 数据

本文介绍如何使用HIDAPI在Qt环境中改进读取HID设备数据的功能。原有的read方法需要多次点击按钮才能接收完整数据包,通过设置hid_set_nonblocking将接收模式改为阻塞,实现连续读取。提出了两种优化方案:一是根据预设的报文总长度判断何时停止接收,二是设定特定的数据结束符来控制接收结束。
摘要由CSDN通过智能技术生成

date:2017/04/12 11:10

调用HIDAPI可实现读数据功能,但是功能十分单一,无法满足需求。

最简单的调用如下:

1 voidWidget::myhid_read(){2 res = hid_read(handle,buf_IN,2);3 for(int i = 0;i < 2;i++){4 qDebug("buf[%d]:0x%02x",i,buf_IN[i]);5 }6 }

使用按钮click()操作调用该方法:

1 voidWidget::on_readButton_clicked()2 {3 qDebug("read data.");4 myhid_read();5 }

但是使用的时候发现,每次点击read按钮运行一次myhid_read(),输出一个包的数据。hid设备产生了多少个数据包就要点多少次按钮才能全部接收。因此需要对它进行改造。

1 voidWidget::myhid_read(){2 qDebug("hid read start");3 res = hid_set_nonblocking(handle, 0);4

5 while (1) {6 res = hid_read(handle,buf_IN,2);7 for(int i = 0;i < 2;i++){8 qDebug("buf[%d]:0x%02x",i,buf_IN[i]);9 }10 }11 }

这里第3行设置接收为阻塞式,HIDAPI文档说明如下:

/** @brief Set the device handle to be non-blocking.

In non-blocking mode calls to hid_read() will return

immediately with a value of 0 if there is no data to be

read. In blocking mode, hid_read() will wait (block) until

there is data to read before returning.

Nonblocking can be turned on and off at any time.

@ingroup API

@param device A device handle returned from hid_open().

@param nonblock enable or not the nonblocking reads

- 1 to enable nonblocking

- 0 to disable nonblocking.

@returns

This function returns 0 on success and -1 on error.*/

设置阻塞后,点击read按钮,开始循环接收数据。但是未设置终止标志,即启动接收后软件一直等待接收数据直到退出软件。

现考虑:

1、提取报文数据总长度做判断量,接收包数与总包数相等则退出;

2、设置数据结束符,接收到特定结束符则退出接收。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值