libusb的用处蛮多的,libusb从入门开始学起,也是作为学习开源库的一点经验。
libusb的安装网络上大把的,这里为了先熟悉库,采用了偷懒的办法:直接apt-get install .
直接在终端输入:
sudo apt-get install libusb-dev
sudo apt-get install libusb-1.0-0-dev
完成后,新建一个C文件:
#include <unistd.h>
#include <stdio.h>
#include <libusb-1.0/libusb.h>
// First, use "lsusb" see vid and pid.
// there is my printer(hp deskjet 1010) vid and pid.
#define VID 0x05e3
#define PID 0x0723
static int device_satus(libusb_device_handle *hd)
{
int interface = 0;
unsigned char byte;
libusb_control_transfer(hd, LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
LIBUSB_REQUEST_CLEAR_FEATURE,
0,
interface,
&byte, 1, 5000);
printf("status:0x%x\n", byte);
/**
* byte
* normal:0x18
* other :0x10
*/
return 0;
}
int main() {
libusb_device **devs; //pointer to pointer of device, used to retrieve a list of devices
libusb_device_handle *dev_handle; //a device handle
libusb_context *ctx = NULL; //a libusb session
int r; //for return values
ssize_t cnt; //holding number of devices in list
r = libusb_init(&ctx); //initialize the library for the session we just declared
if(r < 0) {
perror("Init Error\n"); //there was an error
return 1;
}
libusb_set_debug(ctx, LIBUSB_LOG_LEVEL_INFO); //set verbosity level to 3, as suggested in the documentation
cnt = libusb_get_device_list(ctx, &devs); //get the list of devices
if(cnt < 0) {
perror("Get Device Error\n"); //there was an error
return 1;
}
printf("%d Devices in list.\n", cnt);
dev_handle = libusb_open_device_with_vid_pid(ctx, VID, PID); //these are vendorID and productID I found for my usb device
if(dev_handle == NULL)
perror("Cannot open device\n");
else
printf("Device Opened\n");
libusb_free_device_list(devs, 1); //free the list, unref the devices in it
if(libusb_kernel_driver_active(dev_handle, 0) == 1) { //find out if kernel driver is attached
printf("Kernel Driver Active\n");
if(libusb_detach_kernel_driver(dev_handle, 0) == 0) //detach it
printf("Kernel Driver Detached!\n");
}
r = libusb_claim_interface(dev_handle, 0); //claim interface 0 (the first) of device (mine had jsut 1)
if(r < 0) {
perror("Cannot Claim Interface\n");
return 1;
}
printf("Claimed Interface\n");
device_satus(dev_handle);
libusb_close(dev_handle); //close the device we opened
libusb_exit(ctx); //needs to be called to end the
return 0;
}
注意上述代码中的VID和PID分别是制造商和产品ID:可以通过
cd /sys/kernel/debug
cat usb/devices
Ubuntu上输出如下:
T: Bus=01 Lev=01 Prnt=01 Port=01 Cnt=02 Dev#= 7 Spd=480 MxCh= 0
D: Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs= 1
P: Vendor=05e3 ProdID=0723 Rev=94.51
S: Manufacturer=Generic
S: Product=USB Storage
S: SerialNumber=000000009451
C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=500mA
I:* If#= 0 Alt= 0 #EPs= 2 Cls=08(stor.) Sub=06 Prot=50 Driver=usb-storage
E: Ad=81(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E: Ad=02(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
第三行的P:
Vendor就是VID, ProdID就是PID
P: Vendor=05e3 ProdID=0723
修正代码中的VID和PID就可以编译了。
注意编译的时候需要链接库 -lusb-1.0:
gcc usb.c -lusb-1.0