1.libusb 下载 ,选择编译好的二进制文件,libusb-1.0.26-binaries.7z
libusb Activity
2. 解压
3. 在 Qt Widgets Application 或者 Qt Console Application 工程中导入库,Qt 使用的是 minggw 64编译器,所以选择libusb-MinGW-x64。
把 libusb-1.0.a 和 libusb.h 放入工程。
4. 驱动转换,把libusb驱动转换成Windows的WinUSB驱动。
Zadig - USB driver installation made easy
Zadig是USB驱动安装变得更容易。
Zadig是一个安装通用USB驱动程序的Windows应用程序,诸如WinUSB,libusb-win32/libusb0.sys,libusbK,可以帮助你快速的使用USB设备。
选择 Options -> List All Devices 选择需要通信的USB设备 -> install driver
5. 函数介绍
玩转USB HID系列:libusb函数介绍-CSDN博客
6.测试代码
#include <stdio.h>
#include <libusb.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#define MAX_TX_SIZE 239*27
#define MAX_RX_SIZE 8000
#define MAX_FILE_SIZE 1024*1024*300
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int ret = 1;
libusb_context *ctx = NULL;
libusb_device_handle *dev_handle = NULL;
if(libusb_init(&ctx) < 0)
{
printf("init fail\r\n");
return 1;
}
else
{
printf("init Successful\r\n");
}
dev_handle = libusb_open_device_with_vid_pid(ctx, 0x33AA, 0x0000);
if(dev_handle == NULL)
{
printf("device is not open\r\n");
return 1;
}
else
{
printf("Device Opened\n");
}
if(libusb_kernel_driver_active(dev_handle, 0) == 1)
{
printf("Kernel Driver Active\n");
if(libusb_detach_kernel_driver(dev_handle, 0) == 0)
{
printf("Kernel Driver Detached!\n");
}
}
ret = libusb_claim_interface(dev_handle, 0);
if(ret < 0)
{
perror("Cannot Claim Interface\n");
return 1;
}
int transferred = 0;
uint8_t sendcmd[MAX_TX_SIZE] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08};
uint8_t readbuf[MAX_RX_SIZE] = {0};
for(int i=0; i<163; i++)
{
ret = libusb_bulk_transfer(dev_handle, 0x02, sendcmd, sizeof(sendcmd), &transferred, 0);
//printf("write num=%d\r\n",transferred);
if(ret==0 && transferred==sizeof(sendcmd))
{
// printf("write Successful!\n");
}
else
{
printf("write error!\n");
}
ret = libusb_bulk_transfer(dev_handle, 0x82, readbuf, sizeof(readbuf), &transferred, 0);
if (ret != 0)
{
printf("failed to read \n");
}
else
{
printf("read num=%d\r\n", transferred);
}
}
ret = libusb_release_interface(dev_handle, 0);
if(ret != 0)
{
printf("Cannot Released Interface!\n");
}
else
{
printf("Released Interface!\n");
}
libusb_close(dev_handle);
libusb_exit(ctx);
return a.exec();
}