在Ubuntu上使用libusb读写USB设备需要安装libusb库和libusb开发工具。以下是在Ubuntu上读写USB设备的简单步骤:
sudo apt-get update
sudo apt-get install libusb-1.0-0 libusb-1.0-0-dev
#include <stdio.h>
#include <libusb-1.0/libusb.h>
int main() {
libusb_device **devs;
libusb_device_handle *dev_handle;
libusb_context *ctx = NULL;
// Initialize libusb
if (libusb_init(&ctx) < 0) {
fprintf(stderr, "Error initializing libusb\n");
return 1;
}
// Get the list of USB devices
ssize_t count = libusb_get_device_list(ctx, &devs);
if (count < 0) {
fprintf(stderr, "Error getting device list\n");
return 1;
}
// Open the USB device
dev_handle = libusb_open_device_with_vid_pid(ctx, VENDOR_ID, PRODUCT_ID);
if (dev_handle == NULL) {
fprintf(stderr, "Error opening device\n");
return 1;
}
// Read the device descriptor
struct libusb_device_descriptor desc;
if (libusb_get_device_descriptor(libusb_get_device(dev_handle), &desc) < 0) {
fprintf(stderr, "Error getting device descriptor\n");
return 1;
}
printf("Device Descriptor:\n");
printf("Vendor ID: %04x\n", desc.idVendor);
printf("Product ID: %04x\n", desc.idProduct);
// Clean up
libusb_close(dev_handle);
libusb_free_device_list(devs, 1);
libusb_exit(ctx);
return 0;
}
gcc -o usb_example usb_example.c -lusb-1.0
./usb_example
这样就可以使用libusb在Ubuntu上读取USB设备的描述符。您可以根据需要修改程序来执行其他USB设备操作,如读写数据等。