QT开发之HID通信

使用开源的hidapi库来实现hid通信

下载地址:https://github.com/libusb/hidapi

这个版本编译器是VS2015

1、生成库

直接运行,然后生成Debug或者Release版本都可以,里面会生成hidapi.dll、hidapi.lib、

hidapi.h:头文件在hidapi文件夹中

2、使用

在QT中创建一个新才工程,然后将这三个文件放到项目文件中

.pro中添加

HEADERS += hidapi.h//添加头文件
LIBS += -L$$_PRO_FILE_PWD_/ -lhidapi//添加库

 

main.cpp

注意PID和VID都是16进制

#include "mainwindow.h"
#include <QApplication>
#include <stdio.h>
#include <stdlib.h>
#include "hidapi.h"

#define MAX_STR 512

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();


    //添加的代码
    int res;
    unsigned char buf[64];//一次只能发64,如果要发送512个字节需要合并起来
    memset(buf, 0, 64);

    wchar_t wstr[MAX_STR];
    hid_device *handle;
    int i;

    // Open the device using the VID, PID,
    // and optionally the Serial number.
    handle = hid_open(0x0111, 0x2222, NULL);

    // Read the Manufacturer String
    res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
    wprintf(L"Manufacturer String: %s\n", wstr);

    // Read the Product String
    res = hid_get_product_string(handle, wstr, MAX_STR);
    wprintf(L"Product String: %s\n", wstr);

    // Read the Serial Number String
    res = hid_get_serial_number_string(handle, wstr, MAX_STR);
    wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr);

    // Read Indexed String 1
    res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
    wprintf(L"Indexed String 1: %s\n", wstr);

    // Toggle LED (cmd 0x80). The first byte is the report number (0x0).
    //
    buf[0] = 0x0;
    buf[1] = 0x80;
    res = hid_write(handle, buf, 65);//需要加一位

    // Request state (cmd 0x81). The first byte is the report number (0x0).
    //如果是和设备联机,第一包数据可以用来获取设备名称、版本等信息,然后读取返回来判断是否正确,再进行后面的通信操作
    buf[0] = 0x0;
    buf[1] = 0x81;
    res = hid_write(handle, buf, 65);

    // Read requested state
    hid_read(handle, buf, 65);

    // Print out the returned buffer.
    for (i = 0; i < 4; i++)
    {
        printf("buf[%d]: %d\n", i, buf[i]);
    }

    return a.exec();
}

3、获取PID和VID

将设备连接到电脑后,需要知道设备的PID和VID才能联机

我的电脑->管理->设备管理器->人体学输入设备(通道拔插找到那个是你联机的设备)->右键设备属性->详细信息->属性里面选择硬件id,然后就可以看到PID和VID了

4、通信

这个时候需要使用一个USB数据监控软件,来查看通信的数据,这里推荐使用Bus Hpund,自行百度下载

OUT代表的是上位机发送的数据

IN代表的是下位机发送的数据

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值