废话不多说,直接贴代码
#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>
#define VENDOR_ID 0x1a86
#define PRODUCT_ID 0x7523
#define ENDPOINT_ADDRESS 0x81
int main() {
libusb_device_handle* dev_handle;
int ret;
// 初始化libusb库
ret = libusb_init(NULL);
if (ret < 0) {
fprintf(stderr, "无法初始化libusb库\n");
return 1;
}
// 打开USB设备
dev_handle = libusb_open_device_with_vid_pid(NULL, VENDOR_ID, PRODUCT_ID);
if (dev_handle == NULL) {
fprintf(stderr, "无法打开USB设备\n");
libusb_exit(NULL);
return 1;
}
// 设置USB设备配置
ret = libusb_set_configuration(dev_handle, 1);
if (ret < 0) {
fprintf(stderr, "无法设置USB设备配置\n");
libusb_close(dev_handle);
libusb_exit(NULL);
return 1;
}
// 分配并设置USB设备接口
ret = libusb_claim_interface(dev_handle, 0);
if (ret < 0) {
fprintf(stderr, "无法设置USB设备接口\n");
libusb_close(dev_handle);
libusb_exit(NULL);
return 1;
}
// 发送命令
unsigned char command[] = "Hello, USB!";
int bytes_written;
ret = libusb_bulk_transfer(dev_handle, ENDPOINT_ADDRESS, command, sizeof(command), &bytes_written, 0);
if (ret < 0) {
fprintf(stderr, "无法发送命令\n");
libusb_release_interface(dev_handle, 0);
libusb_close(dev_handle);
libusb_exit(NULL);
return 1;
}
// 释放USB设备接口和关闭USB设备
libusb_release_interface(dev_handle, 0);
libusb_close(dev_handle);
// 关闭libusb库
libusb_exit(NULL);
return 0;
}