Teensy 3.1 and java USB reader

Status
Not open for further replies.

bpoultier

Member
Hi all,

I can't obtain my Teensy in the usb list of connected device to my MacBook Air. The java rxtx library is used in my project.
When my mobile is plugged, it's appear in the list. In doubt, I've unload Teensy uploader program but nothing change.
The Teensy module appears in the device list under "System Info"
Anyone can help me ? If you advise me that I will need to change rxtx lib by another, it's not a problem ;-)

The test source is here:

Code:
package teensy;

import gnu.io.CommPortIdentifier;
import java.util.Enumeration;

// don’t forget -Djava.library.path= for the jni access path
/**
 * Et merde !!!
 * Je cherche mon teensy …
 **/
public class Usbsearch {
	private Enumeration ports = null;
	
    //search for all the serial ports
    public void searchForPorts(){
        ports = CommPortIdentifier.getPortIdentifiers();

        while (ports.hasMoreElements()){
            CommPortIdentifier curPort = (CommPortIdentifier)ports.nextElement();

            //get only serial ports
            if (curPort.getPortType() == CommPortIdentifier.PORT_SERIAL){
                System.out.println( curPort.getName() );
            }
        }
    }
    
	public static void main(String[] args){
		Usbsearch us = new Usbsearch();
		us.searchForPorts();
	}
}

Thank you. Bruno.
 
Do you have a Serial class included in your teensy code? Have you set the USB Type to serial in the arduino types? Are you running the Teensy at less than 24mhz? And why are you swearing in your code :p
 
Hi all,

@jonhnyfp, please see my test source here. The part of usb dialogue come from Teensy example and the program can push all data
to the "Monitor Serie" as you can see in the screen shot below:
Capture d’écran 2014-10-15 à 16.28.30.png


Code:
void setup(){                
  Serial.begin(38400);
}

int val; float v = 0.0F;
const float VREF = 5.0F;
const float RES = 1024.0F;

void loop(){
  val = analogRead(0);
  v = ( VREF * (float) val ) / RES;
  Serial.print(val);
  Serial.print(" -> analog 0 is: ");
  Serial.println(v);
  delay(10);
}


I imagine that the "Monitor Serie" (Serial Monitor) read all incoming data via the usb, no ?
Thank you. Bruno.
 
Did you have the Serial Monitor and Ardunio open at the same time as running your Java program? Try programming the Teensy and shutdown anything related to Arduino IDE before connecting your program, just incase of locks.
 
Hi,

Yes, the Serial Monitor has been closed to do a new test but nothing. I've beginning to test another java and jni lib that offers a low level API.
May be is better than the hight level. I don't known but if it's work fine, I'll post the source.

But if you have a track to help me ;-)

Bruno.
 
Hi all,

I confirm that I've a problem with Teensy on my MacBook laptop ( OS X 10.9.4 )
Now I can see all USB devices with usb4java lib with java program (that it come from usb4java sample) and I can see my Teensy 3.1.

The search result is (only for the interesting Teensy):
Code:
Device 020/012
Connected to port: 2
Parent: 020/129
Speed: Full
Device Descriptor:
  bLength                 18
  bDescriptorType          1
  bcdUSB                2.00
  bDeviceClass             0 Per Interface
  bDeviceSubClass          0
  bDeviceProtocol          0
  bMaxPacketSize0         64
  idVendor            0x16c0
  idProduct           0x0486
  bcdDevice             1.00
  iManufacturer            1 Teensyduino
  iProduct                 2 Teensyduino RawHID
  iSerial                  3 484590
  bNumConfigurations       1
  Configuration Descriptor:
    bLength                  9
    bDescriptorType          2
    wTotalLength            73
    bNumInterfaces           2
    bConfigurationValue      1
    iConfiguration           0
    bmAttributes          0xc0
      Self Powered
    bMaxPower              100mA
    extralen                 0
    extra:
  
  Interface:
    numAltsetting          1
  Interface Descriptor:
    bLength                  9
    bDescriptorType          4
    bInterfaceNumber         0
    bAlternateSetting        0
    bNumEndpoints            2
    bInterfaceClass          3 HID
    bInterfaceSubClass       0
    bInterfaceProtocol       0
    iInterface               0
    extralen                 9
    extra:
      09 21 11 01 00 01 22 1c 00
  Endpoint Descriptor:
    bLength                  7
    bDescriptorType          5
    bEndpointAddress      0x83  EP 3 IN
    bmAttributes             3
      Transfer Type             Interrupt
      Synch Type                None
      Usage Type                Data
    wMaxPacketSize          64
    bInterval                1
    extralen                 0
    extra:
  
  Endpoint Descriptor:
    bLength                  7
    bDescriptorType          5
    bEndpointAddress      0x04  EP 4 OUT
    bmAttributes             3
      Transfer Type             Interrupt
      Synch Type                None
      Usage Type                Data
    wMaxPacketSize          64
    bInterval                1
    extralen                 0
    extra:
  
  Interface:
    numAltsetting          1
  Interface Descriptor:
    bLength                  9
    bDescriptorType          4
    bInterfaceNumber         1
    bAlternateSetting        0
    bNumEndpoints            2
    bInterfaceClass          3 HID
    bInterfaceSubClass       0
    bInterfaceProtocol       0
    iInterface               0
    extralen                 9
    extra:
      09 21 11 01 00 01 22 21 00
  Endpoint Descriptor:
    bLength                  7
    bDescriptorType          5
    bEndpointAddress      0x81  EP 1 IN
    bmAttributes             3
      Transfer Type             Interrupt
      Synch Type                None
      Usage Type                Data
    wMaxPacketSize          64
    bInterval                1
    extralen                 0
    extra:
  
  Endpoint Descriptor:
    bLength                  7
    bDescriptorType          5
    bEndpointAddress      0x02  EP 2 OUT
    bmAttributes             3
      Transfer Type             Interrupt
      Synch Type                None
      Usage Type                Data
    wMaxPacketSize          32
    bInterval                2
    extralen                 0
    extra:

___________________________________________________


Code:
import org.usb4java.ConfigDescriptor;
import org.usb4java.Context;
import org.usb4java.DescriptorUtils;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.DeviceList;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;

/**
 * Dumps the descriptors of all available connected devices.
 * This source come from usb4java website without 
 * @author Klaus Reimer <k@ailis.de>
 */
public class SearchTeensyDevices
{
    /**
     * Dumps all configuration descriptors of the specified device. Because
     * libusb descriptors are connected to each other (Configuration descriptor
     * references interface descriptors which reference endpoint descriptors)
     * dumping a configuration descriptor also dumps all interface and endpoint
     * descriptors in this configuration.
     * 
     * @param device
     *            The USB device.
     * @param numConfigurations
     *            The number of configurations to dump (Read from the device
     *            descriptor)
     */
    public static void dumpConfigurationDescriptors(final Device device,
        final int numConfigurations)
    {
        for (byte i = 0; i < numConfigurations; i += 1)
        {
            final ConfigDescriptor descriptor = new ConfigDescriptor();
            final int result = LibUsb.getConfigDescriptor(device, i, descriptor);
            if (result < 0){
                throw new LibUsbException("Unable to read config descriptor",
                    result);
            }
            try{
                System.out.println(descriptor.dump().replaceAll("(?m)^",
                    "  "));
                System.out.println("___________________________________________________");
            }
            finally{
                // Ensure that the config descriptor is freed
                LibUsb.freeConfigDescriptor(descriptor);
            }
        }
    }

    /**
     * Dumps the specified device to stdout.
     * 
     * @param device
     *            The device to dump.
     */
    public static void dumpDevice(final Device device)
    {
        // Dump device address and bus number
        final int address = LibUsb.getDeviceAddress(device);
        final int busNumber = LibUsb.getBusNumber(device);
        System.out.println(String
            .format("Device %03d/%03d", busNumber, address));

        // Dump port number if available
        final int portNumber = LibUsb.getPortNumber(device);
        if (portNumber != 0)
            System.out.println("Connected to port: " + portNumber);

        // Dump parent device if available
        final Device parent = LibUsb.getParent(device);
        if (parent != null)
        {
            final int parentAddress = LibUsb.getDeviceAddress(parent);
            final int parentBusNumber = LibUsb.getBusNumber(parent);
            System.out.println(String.format("Parent: %03d/%03d",
                parentBusNumber, parentAddress));
        }

        // Dump the device speed
        System.out.println("Speed: "
            + DescriptorUtils.getSpeedName(LibUsb.getDeviceSpeed(device)));

        // Read the device descriptor
        final DeviceDescriptor descriptor = new DeviceDescriptor();
        int result = LibUsb.getDeviceDescriptor(device, descriptor);
        if (result < 0)
        {
            throw new LibUsbException("Unable to read device descriptor",
                result);
        }

        // Try to open the device. This may fail because user has no
        // permission to communicate with the device. This is not
        // important for the dumps, we are just not able to resolve string
        // descriptor numbers to strings in the descriptor dumps.
        DeviceHandle handle = new DeviceHandle();
        result = LibUsb.open(device, handle);
        if (result < 0)
        {
            System.out.println(String.format("Unable to open device: %s. "
                + "Continuing without device handle.",
                LibUsb.strError(result)));
            handle = null;
        }

        // Dump the device descriptor
        System.out.print(descriptor.dump(handle));

        // Dump all configuration descriptors
        dumpConfigurationDescriptors(device, descriptor.bNumConfigurations());

        // Close the device if it was opened
        if (handle != null)
        {
            LibUsb.close(handle);
        }
    }

    /**
     * Main method.
     * 
     * @param args
     *            Command-line arguments (Ignored)
     */
    public static void main(final String[] args)
    {
        // Create the libusb context
        final Context context = new Context();

        // Initialize the libusb context
        int result = LibUsb.init(context);
        if (result < 0)
        {
            throw new LibUsbException("Unable to initialize libusb", result);
        }

        // Read the USB device list
        final DeviceList list = new DeviceList();
        result = LibUsb.getDeviceList(context, list);
        if (result < 0)
        {
            throw new LibUsbException("Unable to get device list", result);
        }

        try
        {
            // Iterate over all devices and dump them
            for (Device device: list)
            {
                dumpDevice(device);
            }
        }
        finally
        {
            // Ensure the allocated device list is freed
            LibUsb.freeDeviceList(list, true);
        }
        
        // Deinitialize the libusb context
        LibUsb.exit(context);
    }
}

Under Mac OS X, It seem that we don't have a right to "Claim" the interface. So my question is what is the InterfaceNumber that must be called to work in HID via a java program.
Do I need to work with EndPoints ?

Code:
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import org.usb4java.BufferUtils;
import org.usb4java.Context;
import org.usb4java.Device;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;

/**
 * Demonstrates how to do synchronous bulk transfers.
 * 
 * This part come from Klaus Reimer.
 * VID, PID en INTERFACE has been changed.
 * 
 * @author Klaus Reimer <k@ailis.de>
 */
public class HidUsbDevice {
	static Context context = new Context();
	
    /** The vendor ID of the Teensy 3.1. */
    private static final short VENDOR_ID = 0x16c0;

    /** The product ID of the Teensy 3.1. */
    private static final short PRODUCT_ID = 0x0486;

    /** The Teensy HID interface number  ( Teensy had 2 interfaces )**/
    private static final byte INTERFACE = 1; // the iface 1 is HID ????

    /** The Teensy 3.1 input endpoint  **/
    private static final byte IN_ENDPOINT = (byte) 0x83;  // EP 3 IN

    /** The Teensy 3.1 output endpoint **/
    private static final byte OUT_ENDPOINT = 0x04;  // EP 4 OUT;

    /** The communication timeout in milliseconds. */
    private static final int TIMEOUT = 1000;

    /**
     * Writes some data to the device.
     * 
     * @param handle
     *            The device handle.
     * @param data
     *            The data to send to the device.
     */
    public static void write(DeviceHandle handle, byte[] data)
    {
        ByteBuffer buffer = BufferUtils.allocateByteBuffer(data.length);
        buffer.put(data);
        IntBuffer transferred = BufferUtils.allocateIntBuffer();
        int result = LibUsb.bulkTransfer(handle, OUT_ENDPOINT, buffer,
            transferred, TIMEOUT);
        if (result != LibUsb.SUCCESS)
        {
            throw new LibUsbException("Unable to send data", result);
        }
        System.out.println(transferred.get() + " bytes sent to device");
    }

    /**
     * Reads some data from the device.
     * 
     * @param handle
     *            The device handle.
     * @param size
     *            The number of bytes to read from the device.
     * @return The read data.
     */
    public static ByteBuffer read(DeviceHandle handle, int size)
    {
        ByteBuffer buffer = BufferUtils.allocateByteBuffer(size).order(
            ByteOrder.LITTLE_ENDIAN);
        IntBuffer transferred = BufferUtils.allocateIntBuffer();
        int result = LibUsb.bulkTransfer(handle, IN_ENDPOINT, buffer,
            transferred, TIMEOUT);
        if (result != LibUsb.SUCCESS)
        {
            throw new LibUsbException("Unable to read data", result);
        }
        System.out.println(transferred.get() + " bytes read from device");
        return buffer;
    }

    /**
     * Main method.
     * 
     * @param args
     *            Command-line arguments (Ignored)
     * @throws Exception
     *             When something goes wrong.
     */
    public static void main(String[] args) throws Exception
    {
        // Initialize the libusb context
        int result = LibUsb.init(null);
        if (result != LibUsb.SUCCESS)
        {
            throw new LibUsbException("Unable to initialize libusb", result);
        }

        // Open test device (Samsung Galaxy Nexus)
        DeviceHandle devicehandle = LibUsb.openDeviceWithVidPid(null, VENDOR_ID, PRODUCT_ID);
        Device teensy = LibUsb.getDevice(devicehandle);
        System.out.println("Max packet size: " + LibUsb.getDeviceSpeed(  teensy) );
        
        if (devicehandle == null){
            System.err.println("Teensy device is not found.");
            System.exit(1);
        }
        else
        	System.out.println("Teensy device is openned: " + devicehandle );
        	// Device teensy = LibUsb.getDevice(handle);
        	
        // Claim the Teensy interface. Under some OS, the kernel had already claimed.
        // Try to detach before continue.
        result = LibUsb.claimInterface(devicehandle, INTERFACE);

        if (result != LibUsb.SUCCESS){
        		boolean detachCapability = LibUsb.hasCapability(LibUsb.CAP_SUPPORTS_DETACH_KERNEL_DRIVER);
        		result = LibUsb.kernelDriverActive(devicehandle, INTERFACE);
        		
        		if ( false == detachCapability )
        			throw new LibUsbException("Enable to detach Teensy. ", (detachCapability == true ? 0: 1) );
        		
        		if ( result != LibUsb.SUCCESS && detachCapability == true )
        			throw new LibUsbException("Unable to detach interface", result);
        		
        		result = LibUsb.detachKernelDriver(devicehandle,  INTERFACE);
        	    if (result != LibUsb.SUCCESS) 
        	    	throw new LibUsbException("Unable to detach kernel driver", result);
        	
        }

        // Try to read data from Teensy/HID
        @SuppressWarnings("unused")
        ByteBuffer data = read(devicehandle, 64);
        System.out.println( new String( data.array() ) );
        
        
        // Release the Teensy interface
        result = LibUsb.releaseInterface(devicehandle, INTERFACE);
        if (result != LibUsb.SUCCESS)
        {
            throw new LibUsbException("Unable to release interface", result);
        }

        // Close the device
        LibUsb.close(devicehandle);

        // Deinitialize the libusb context
        LibUsb.exit(null);
    }
}

Someone can help me ?
In advance, many thanks. Bruno.
 
Last edited:
Hi all,

I'm always on my problem, It seem that Teensy does not appear as 'serial modem' in /dev/cu.xxxxxxxx even I can
find out the Teensy in this listing:

Code:
ioreg -c IOSerialBSDClient | grep -i usb
    | | | | +-o AppleUSBXHCI  <class AppleUSBXHCI, id 0x100000231, registered, matched, active, busy 0 (84937 ms), retain 17>
    | | | |   +-o XHCI Root Hub SS Simulation@14  <class IOUSBRootHubDevice, id 0x10000028a, registered, matched, active, busy 0 (608 ms), retain 11>
    | | | |   | +-o AppleUSBHub  <class AppleUSBHub, id 0x10000028c, registered, matched, active, busy 0 (0 ms), retain 9>
    | | | |   | +-o IOUSBInterface@0  <class IOUSBInterface, id 0x10000028e, !registered, !matched, active, busy 0, retain 7>
    | | | |   +-o XHCI Root Hub USB 2.0 Simulation@14  <class IOUSBRootHubDevice, id 0x10000028f, registered, matched, active, busy 0 (603 ms), retain 13>
    | | | |   | +-o AppleUSBHub  <class AppleUSBHub, id 0x100000291, registered, matched, active, busy 0 (0 ms), retain 12>
    | | | |   | +-o IOUSBInterface@0  <class IOUSBInterface, id 0x100000293, !registered, !matched, active, busy 0, retain 7>
    | | | |   +-o Card Reader@15300000  <class IOUSBDevice, id 0x10007add3, registered, matched, active, busy 0 (2175 ms), retain 9>
    | | | |   | +-o IOUSBCompositeDriver  <class IOUSBCompositeDriver, id 0x10007adf5, !registered, !matched, active, busy 0, retain 4>
    | | | |   | +-o IOUSBInterface@0  <class IOUSBInterface, id 0x10007adf6, registered, matched, active, busy 0 (306 ms), retain 8>
    | | | |   |   +-o com_apple_driver_AppleUSBCardReaderUMC  <class com_apple_driver_AppleUSBCardReaderUMC, id 0x10007adf8, registered, matched, active, busy 0 (290 ms), retain 10>
    | | | |   |       +-o com_apple_driver_AppleUSBCardReaderSBC  <class com_apple_driver_AppleUSBCardReaderSBC, id 0x10007ae05, !registered, !matched, active, busy 0 (0 ms), retain 8>
    | | | |   +-o BRCM20702 Hub@14300000  <class IOUSBHubDevice, id 0x10007add5, registered, matched, active, busy 0 (10 ms), retain 11>
    | | | |   | +-o AppleUSBHub  <class AppleUSBHub, id 0x10007add7, registered, matched, active, busy 0 (0 ms), retain 9>
    | | | |   | +-o IOUSBInterface@0  <class IOUSBInterface, id 0x10007add9, !registered, !matched, active, busy 0, retain 7>
    | | | |   +-o Bluetooth USB Host Controller@14330000  <class IOUSBDevice, id 0x10007addc, registered, matched, active, busy 0 (1372 ms), retain 12>
    | | | |   | +-o BroadcomBluetoothHostControllerUSBTransport  <class BroadcomBluetoothHostControllerUSBTransport, id 0x10007adfd, registered, matched, active, busy 0 (0 ms), retain 9>
    | | | |   | +-o IOUSBInterface@0  <class IOUSBInterface, id 0x10007ae01, !registered, !matched, active, busy 0, retain 7>
    | | | |   | +-o IOUSBInterface@1  <class IOUSBInterface, id 0x10007ae02, !registered, !matched, active, busy 0, retain 7>
    | | | |   | +-o IOUSBInterface@2  <class IOUSBInterface, id 0x10007ae03, !registered, !matched, active, busy 0, retain 6>
    | | | |   | +-o IOUSBInterface@3  <class IOUSBInterface, id 0x10007ae04, !registered, !matched, active, busy 0, retain 6>
    | | | |   +-o Teensyduino RawHID@14100000  <class IOUSBDevice, id 0x1000851f6, registered, matched, active, busy 0 (211 ms), retain 12>
    | | | |     +-o IOUSBCompositeDriver  <class IOUSBCompositeDriver, id 0x1000851fa, !registered, !matched, active, busy 0, retain 4>
    | | | |     +-o IOUSBInterface@0  <class IOUSBInterface, id 0x1000851fb, registered, matched, active, busy 0 (21 ms), retain 9>
    | | | |     | +-o IOUSBHIDDriver  <class IOUSBHIDDriver, id 0x1000851fe, registered, matched, active, busy 0 (4 ms), retain 11>
    | | | |     +-o IOUSBInterface@1  <class IOUSBInterface, id 0x1000851fc, registered, matched, active, busy 0 (17 ms), retain 9>
    | | | |       +-o IOUSBHIDDriver  <class IOUSBHIDDriver, id 0x100085205, registered, matched, active, busy 0 (3 ms), retain 12>

The ls command done this:
Code:
ls -l /dev/cu*
crw-rw-rw-  1 root  wheel   19,   1 24 sep 14:06 /dev/cu.Bluetooth-Incoming-Port
crw-rw-rw-  1 root  wheel   19,   3 24 sep 14:06 /dev/cu.Bluetooth-Modem
and I don't see the serial device as /dev/cu.xxxxxx for the Arduino or Teensy.

Thanks for your help ;-)
 
Did you select USB TYPE to be serial? I believe the default is RAW HID, which does not provide a serial connection. I don't have a Mac, but under Linux, the Teensy won't show up as a serial device (i.e. /dev/ttyACM0) unless I select the USB serial type. In addition, I have to set the udev rules so that normal users can see it (and the modem manager doesn't try to treat it like a USB modem). Perhaps there is something similar in the Mac.
 
Last edited:
Unless you select USB serial type in which? In Linux, Teensyduino, or Java?

You select USB serial type in the Arduino IDE you use to program the Teensy 3.0/3.1. If you are not using the IDE, you need to define USB_SERIAL when you are building the support libraries (cores/teensy3/usb_inst.cpp in particular). You need to re-install the program with the setting, so that it uses the serial code upon startup.
 
Thanks at all for your reply.

I say that I stop the development under Mac to pass to Linux. I think I've tried everything (under OS X) but no results even if I would like
to help someone under Mac.
Under Linux, The Teensy/hidraw is recognized without problem and my project become fine started. I'm not so far to expose my "magnetic deflexion sensor".
Again Thanks for your replies. Bruno.
 
Status
Not open for further replies.
Back
Top