本來是幫朋友寫個RFID讀寫器設備的程序,最開始沒要求USB接口,半路加了這個功能。而且windows版的早都完成了,Linux版的遲遲未做。今天終於抽空將Linux下的usb通信調通,特此記錄一下。
使用libusb做linux下的通信的調試過程大概如下:
1、使用命令行工具lsusb,查看當前設備的通信端點的通信方式。lsusb -v后,在Endpoint中的Transfer Type可以看到,我用的這個設備的通信方式為interrupt,中斷模式。
2、使用lsusb查看輸出端點和輸入端點,記錄端點號。一般情況為,寫設備為0x01(朋友的設備為0x02),讀設備為0x81.
3、查看輸出緩沖區的大小,在寫設備時會用到---絆在這塊時間比較久。
完成了上述三點就可以進行編程了,事例代碼如下:
#include <string.h> #include <stdio.h> #include <libusb-1.0/libusb.h> static libusb_device_handle *dev_handle = NULL; int main() { int i = 0; int ret = 1; int transferred = 0; ssize_t cnt; unsigned char cmd[64] = {0x5A, 0x00, 0x01, 0x02, 0x10, 0x00, 0x05, 0x00, 0x00, 0x00, 0x01, 0x01, 0xF4, 0x87}; // 64為上述第3步獲取到的緩沖區大小 struct libusb_device_descriptor desc; libusb_device **devs; libusb_context *ctx = NULL; ret = libusb_init(NULL); if(ret < 0) { fprintf(stderr, "failed to initialise libusb\n"); return 1; } dev_handle = libusb_open_device_with_vid_pid(NULL, 0x03eb, 0x2421); if(dev_handle == NULL){ perror("Cannot open device\n"); }else{ printf("Device Opened\n"); } if(libusb_kernel_driver_active(dev_handle, 0) == 1) { printf("Kernel Driver Active\n"); if(libusb_detach_kernel_driver(dev_handle, 0) == 0){ printf("Kernel Driver Detached!\n"); } } ret = libusb_claim_interface(dev_handle, 0); if(ret < 0) { perror("Cannot Claim Interface\n"); return 1; } ret = libusb_interrupt_transfer(dev_handle, 0x02, cmd, sizeof(cmd), &transferred, 0); if(ret==0 && transferred==sizeof(cmd_ir_start)){ printf("write Successful!\n"); }else{ printf("write error!\n"); } char buf[1024] = {0}; ret = libusb_interrupt_transfer(dev_handle, 0x81, buf, sizeof(buf), &transferred, 0); if (ret != 0) { printf("failed to read \n"); } ret = libusb_release_interface(dev_handle, 0); if(ret != 0){ printf("Cannot Released Interface!\n"); }else{ printf("Released Interface!\n"); } libusb_close(dev_handle); libusb_exit(ctx); return 0; }