在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設備操作,如讀寫數據等。