用libusb写一个usb通信例子
时间: 2023-12-29 21:25:40 浏览: 173
libusb_example_libusb_USB通信_
5星 · 资源好评率100%
下面是一个利用libusb实现USB通信的例子,本例子实现的是使用USB-HID协议控制一个USB设备的LED灯开关:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libusb-1.0/libusb.h>
#define VENDOR_ID 0x1234
#define PRODUCT_ID 0x5678
#define HID_GET_REPORT 0x01
#define HID_SET_REPORT 0x09
#define REPORT_ID 0x01
static int send_report(libusb_device_handle *handle, const unsigned char *data, int length)
{
int res, transferred;
unsigned char buf[length + 1];
memset(buf, 0, length + 1);
buf[0] = REPORT_ID;
memcpy(&buf[1], data, length);
res = libusb_control_transfer(handle, LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_ENDPOINT_OUT,
HID_SET_REPORT, (REPORT_ID << 8) | 0x00, 0x00, buf, length + 1, 1000);
if (res != length + 1) {
fprintf(stderr, "Error: control transfer failed. %d\n", res);
return -1;
}
res = libusb_interrupt_transfer(handle, 0x81, buf, length + 1, &transferred, 1000);
if (res != 0) {
fprintf(stderr, "Error: interrupt transfer failed. %d\n", res);
return -1;
}
return 0;
}
int main(int argc, char **argv)
{
libusb_device **devs;
libusb_device_handle *handle;
struct libusb_device_descriptor desc;
int r, i, transferred;
ssize_t cnt;
unsigned char data[1];
r = libusb_init(NULL);
if (r < 0) {
fprintf(stderr, "Error: failed to initialize libusb. %d\n", r);
return -1;
}
cnt = libusb_get_device_list(NULL, &devs);
if (cnt < 0) {
fprintf(stderr, "Error: failed to get device list. %d\n", r);
libusb_exit(NULL);
return -1;
}
for (i = 0; i < cnt; i++) {
r = libusb_get_device_descriptor(devs[i], &desc);
if (r < 0) {
fprintf(stderr, "Error: failed to get device descriptor. %d\n", r);
break;
}
if (desc.idVendor == VENDOR_ID && desc.idProduct == PRODUCT_ID) {
r = libusb_open(devs[i], &handle);
if (r < 0) {
fprintf(stderr, "Error: failed to open device. %d\n", r);
break;
}
r = libusb_kernel_driver_active(handle, 0);
if (r == 1) {
r = libusb_detach_kernel_driver(handle, 0);
if (r < 0) {
fprintf(stderr, "Error: failed to detach kernel driver. %d\n", r);
break;
}
}
r = libusb_claim_interface(handle, 0);
if (r < 0) {
fprintf(stderr, "Error: failed to claim interface. %d\n", r);
break;
}
data[0] = 0x01;
send_report(handle, data, sizeof(data));
data[0] = 0x00;
send_report(handle, data, sizeof(data));
libusb_release_interface(handle, 0);
libusb_close(handle);
break;
}
}
libusb_free_device_list(devs, 1);
libusb_exit(NULL);
return 0;
}
```
这个例子打开一个VID为0x1234、PID为0x5678的USB设备,并控制设备的LED灯开关。具体实现过程是:先打开设备、卸载内核驱动和申请接口,然后发送一个开灯的命令和一个关灯的命令,最后释放接口和关闭设备。其中,`send_report`函数用于发送HID报告,通过控制传输和中断传输两个步骤实现。
阅读全文