libusb_Qt使用

本文介绍了如何在Qt项目中使用Libusb库,包括从GitHub下载库、在.pro文件中设置编译参数以及在C++代码中获取和操作USB设备的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Libusb

libusb_github
在这里插入图片描述
建议直接下载库,编译好麻烦

QT调用

.pro文件添加:

win32: LIBS += -L$$PWD/LIB/libusb/x64/ -llibusb-1.0

.cpp调用即可

#include "LIB/libusb/libusb.h"
void class_name::fun(){
	/* 1.  */
    libusb_init(NULL);
    /**/
    struct libusb_device **device_list;
    int num_devices = libusb_get_device_list(NULL, &device_list);
    /**/
    for (int i = 0; i < num_devices; i++)
    {
            struct libusb_device *dev = device_list[i];
            struct libusb_device_descriptor dev_desc;
            libusb_get_device_descriptor(dev, &dev_desc);
            int id_vendor =  dev_desc.idVendor;
            int id_product = dev_desc.idProduct;
            qDebug() << "id_vendor="<<id_vendor;
            qDebug() << "id_product="<<id_product;

            /**/
            struct libusb_device_handle *dev_handle = NULL;
            libusb_open(dev, &dev_handle);  //or
            dev_handle = libusb_open_device_with_vid_pid(NULL, 0x0525, 0xa4a0);
    }
}
分析我的是否合理void HidReader::run() { running = true; if (libusb_init(&ctx) < 0) { qDebug() << "libusb 初始化失败!"; return; } dev_handle = libusb_open_device_with_vid_pid(ctx, VENDOR_ID, PRODUCT_ID); if (!dev_handle) { qDebug() << "无法打开 HID 设备!"; libusb_exit(ctx); return; } // 选择接口0 int r = libusb_claim_interface(dev_handle, 0); if (r != LIBUSB_SUCCESS) { qDebug() << "无法声明接口! 错误代码:" << r; libusb_close(dev_handle); libusb_exit(ctx); return; } unsigned char buffer[64]; // 报告 ID (1 字节) + 数据 (64 字节) int actual_length; qDebug() << "HID 监听线程启动..."; QByteArray lastData; // 记录上次收到的数据 QByteArray data; while (running) { int r = libusb_interrupt_transfer(dev_handle, ENDPOINT_IN, buffer, REPORT_SIZE + 1, &actual_length, 1000); if (r == LIBUSB_SUCCESS) { uint8_t report_id = buffer[0]; switch(report_id) { case 0x1B: data = QByteArray((char*)buffer, actual_length); if (data != lastData) { // 过滤掉重复数据 lastData = data; emit dataReceived(data); } break; case 0x1C: data = QByteArray((char*)buffer, actual_length); if (data != lastData) { // 过滤掉重复数据 lastData = data; emit dataReceived(data); } break; default: qDebug() << "未知报告类型:" << report_id; } } else if (r == LIBUSB_ERROR_TIMEOUT) { continue; // 超时不影响 } else { qDebug() << "HID 读取失败! 错误代码:" << r; running = false; } } libusb_release_interface(dev_handle, 0); libusb_close(dev_handle); libusb_exit(ctx); qDebug() << "HID 监听线程退出!"; }
最新发布
03-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值