hid编程 qt_Qt USBHID—— 读取数据

本文介绍了在Qt环境下使用HIDAPI库进行USB HID设备读取数据的优化过程。最初,通过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.*/

HIDAPI提供两种读设备的方式,阻塞和非阻塞。阻塞是指在进入读设备函数后,直到有数据被读取才退出,而非阻塞则不等待数据的到来,没有数据则返回0

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

现考虑:

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值