62 lines
1.9 KiB
C
62 lines
1.9 KiB
C
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <libusb-1.0/libusb.h>
|
||
|
||
#define VENDOR_ID 0x1a86 // 替换为你的设备 VID
|
||
#define PRODUCT_ID 0x55de // 替换为你的设备 PID
|
||
#define BULK_EP_OUT 0x06 // OUT端点地址(低位为0表示OUT)
|
||
#define INTERFACE_NUMBER 4 // USB接口编号
|
||
|
||
int main(void) {
|
||
libusb_device_handle *handle = NULL;
|
||
int r;
|
||
int transferred;
|
||
unsigned char send_data[] = {0x01, 0x02, 0x03, 0x04, 0x05}; // 要发送的数据
|
||
|
||
// 初始化libusb
|
||
r = libusb_init(NULL);
|
||
if (r < 0) {
|
||
fprintf(stderr, "Failed to init libusb: %s\n", libusb_error_name(r));
|
||
return EXIT_FAILURE;
|
||
}
|
||
|
||
// 打开设备
|
||
handle = libusb_open_device_with_vid_pid(NULL, VENDOR_ID, PRODUCT_ID);
|
||
if (!handle) {
|
||
fprintf(stderr, "Failed to open device\n");
|
||
libusb_exit(NULL);
|
||
return EXIT_FAILURE;
|
||
}
|
||
|
||
// 获取接口权限(可选,部分系统如Linux必须)
|
||
if (libusb_kernel_driver_active(handle, INTERFACE_NUMBER)) {
|
||
libusb_detach_kernel_driver(handle, INTERFACE_NUMBER);
|
||
}
|
||
|
||
r = libusb_claim_interface(handle, INTERFACE_NUMBER);
|
||
if (r < 0) {
|
||
fprintf(stderr, "Failed to claim interface: %s\n", libusb_error_name(r));
|
||
libusb_close(handle);
|
||
libusb_exit(NULL);
|
||
return EXIT_FAILURE;
|
||
}
|
||
|
||
// 发送数据(Bulk OUT)
|
||
r = libusb_bulk_transfer(handle, BULK_EP_OUT, send_data, sizeof(send_data), &transferred, 1000);
|
||
if (r == 0) {
|
||
printf("Sent %d\n", transferred);
|
||
if (transferred != sizeof(send_data)) {
|
||
fprintf(stderr, "Warning: Only %d of %zu bytes sent\n", transferred, sizeof(send_data));
|
||
}
|
||
} else {
|
||
fprintf(stderr, "Failed to send data: %s\n", libusb_error_name(r));
|
||
}
|
||
|
||
// 释放接口 & 关闭
|
||
libusb_release_interface(handle, INTERFACE_NUMBER);
|
||
libusb_close(handle);
|
||
libusb_exit(NULL);
|
||
|
||
return EXIT_SUCCESS;
|
||
}
|