Once the configuration is done, you can write the code (you need to know some basic USB protocol knowledge). For the use of a library, its help documentation is very important and can be found in the libusb-win32 development documentation (http://sourceforge.net/p/libusb-win32/wiki/Documentation/).
Next , analyze the code that uses bulk for data transfer.
When you write code, you first determine Idvendor and the idproduct , and then to determine Bulk The input and output ports of the endpoint ep_in and Ep_out (the PC side is the opposite of the USB device):
#define Idvendor 0x1122#define idproduct 0x3344#define ep_out 0x04#define ep_in 0x83#define my_config 0x01#define my_int 0x00#define BUFFER _size 64
then initialize, and find your own device:
struct Usb_bus *bus;
struct Usb_device *dev;
struct Usb_dev_handle *hdev;
int ret = 0;
Char buffer2[buffer_size] = "Usbkey by Libusb-win32";
Usb_init (); usb_find_busses (); usb_find_devices (); for (bus = usb_get_busses (); bus; bus = bus->next) { for (dev = bus->devices; dev; dev = dev->
>next) {
if(Dev->descriptor.idvendor = = Idvendor && Dev->descriptor.idproduct = = Idproduct) {
//......
}
}
}
After finding your device through Idvendor and idproduct, you can open the device and get a handle to the device Hdev, which can be controlled by the handle:
Hdev = usb_open (dev); if (Hdev = = NULL) { printf ("open error!\n") ; return 1 ;}
To transfer data, you must first call the following two functions for configuration and registration (you can see the Help documentation):
if(Usb_set_configuration (Hdev, My_config) <0) {printf ("Error setting config #%d:%s", My_config, Usb_strerror ()); return 1;}if(Usb_claim_interface (Hdev, My_int) <0) {printf ("error claiming interface #%d:\n%s", My_int, Usb_strerror ()); return 1;}
Where My_config and My_int are separated by the bconfigurationvalue field in descriptor and descriptor Binterfacenumber (the two fields are described in the USB protocol).
You can then use functions for bulk endpoint read and write operations:
ret = Usb_bulk_write (hdev,ep_out,buffer2,buffer_size, +);if(Ret <0) {printf ("ret =%d\n", ret); printf ("Write error:%s\n", Usb_strerror ()); }Else{printf ("SED:%d\n", ret); printf ("SED:%s\n", Buffer2); }ret= Usb_bulk_read (Hdev,ep_in,buffer2,buffer_size, +);if(Ret <0) {printf ("ret =%d\n", ret); printf ("Read error:%s\n", Usb_strerror ());}Else{printf ("REC:%d\n", ret); printf ("REC:%s\n", buffer2);} RET= Usb_bulk_read (Hdev,ep_in,buffer2,buffer_size, +);if(Ret <0) {printf ("ret =%d\n", ret); printf ("Read error:%s\n", Usb_strerror ());}Else{printf ("REC:%d\n", ret); printf ("REC:%s\n", Buffer2);
}
Shut down the device after reading and writing:
Usb_close (Hdev);
Part of the code for the USB hardware device:
Char Buffer[buffer_size]; Usb_init (); while (1"Usbkey inA980" );}
Program Run Result:
Libusb-win32 Study notes (ii)