LibusbJava

libusb for Java

User Tools

Site Tools


first_steps:start

First Steps with LibusbJava

Important note for Windows

  • getDeviceList() of libusb and Device.search() of LibusbJava return the first device with the corresponding VID, PID. In Windows a composite device is represented by multiple devices with the same VID, PID, so you will have to search for the one you want to use (see libusb Mailing List).

The following short example will show you how to use LibusbJava in your Java-Project. The following code describes the required steps to do a bulk transfer to your device.

  1. Create a new Context (initialises the libusb, returns a context)
  2. Search your device, for example via Vendor- and Product-ID
  3. (optionally) get information out of the USB Descriptors
  4. Open your device
  5. Claim the desired interface
  6. write some data with a bulk transfer to your device
  7. Release interface
  8. Close the device
Context useCtx = null;                           
Device usbDev = null;
try {
        useCtx = new Context();                                                  /* 1 */
} catch (LibusbException e) {
        System.out.println("Init failed:");
	e.printStackTrace();
}
 
System.out.println("Search Device:");
try {
	usbDev = Device.search(useCtx, 0x8235, 0x100);                           /* 2 */
 
} catch (LibusbException e) {
	System.out.println("Error occured: search");
	e.printStackTrace();
}
 
if(usbDev == null) return;
 
try {
	usbDev.open();                                                           /* 4 */
	usbDev.claimInterface(0);                                                /* 5 */
	byte[] data = {(byte)0x40, (byte)0x80, (byte)0x12, (byte)0x16};
	int res = usbDev.bulkTransfer(2, data, data.length, 0);                  /* 6 */
	if(res == data.length){
	        System.out.println("Bulk tranfer 1 successful.");
	}
	else{
		System.out.println("Bulk transfer 1 failed.");
	}
	usbDev.reset();
	res = 0;
	res = usbDev.bulkTransfer(2, data, data.length, 0);                      /* 6 */
	if(res == data.length){
		System.out.println("Bulk tranfer 2 successful.");
	}
	else{
		System.out.println("Bulk transfer 2 failed.");
	}
	usbDev.releaseInterface(0);                                              /* 7 */
	usbDev.close();                                                          /* 8 */
	System.out.println("Device closed.");
} catch (LibusbException e) {
	System.out.println("Error occured: transfer");
	e.printStackTrace();
}
first_steps/start.txt · Last modified: 2016/07/12 10:37 by akalberer