Skip to content

7. Multiple Serial ports

Felipe Herranz edited this page Nov 18, 2018 · 1 revision

Multiple Serial ports example

Remember to check the examplemultipleports module for a complete example of how to open two serial ports in the same Android device

Use

Since UsbSerial 5.0.0 a new class SerialPortBuilder allows to easily handling more than one serial port in the same device. First, We need to create the SerialPortBuilder object

Context mContext;
SerialPortCallback serialPortCallback = new SerialPortCallback() {
    @Override
    public void onSerialPortsDetected(List<UsbSerialDevice> serialPorts) {
            //TODO!!
    }
};

...

SerialPortBuilder builder = SerialPortBuilder.createSerialPortBuilder(serialPortCallback);

If you just want to get all the connected devices supported by UsbSerial and setup them on your own using sync/async/IO you can use

List<UsbDevice> possibleSerialPorts = builder.getPossibleSerialPorts(mContext);

But SerialPortBuilder offers the possibility of creating all UsbSerialDevice directly without opening them

builder.getSerialPorts(mContext);

If all ports are going to need the same configuration you can create and open them directly with

builder.openSerialPorts(mContext, 115200,
                UsbSerialInterface.DATA_BITS_8,
                UsbSerialInterface.STOP_BITS_1,
                UsbSerialInterface.PARITY_NONE,
                UsbSerialInterface.FLOW_CONTROL_OFF);

SerialPortBuilder will request permission for each one of the connected devices and if explicit user permission is needed a popup asking for permissions will appear for every connected devices.

When all permissions has been accepted (or rejected) SerialPortCallback will be called

Results will be received in the SerialPortCallback.

SerialPortCallback serialPortCallback = new SerialPortCallback() {
    @Override
    public void onSerialPortsDetected(List<UsbSerialDevice> serialPorts) {
            for(UsbSerialDevice serialDevice : serialPorts){
            if(!serialDevice.isOpen()){
                //TODO: Open device
            }
        }
    }
};

For writing and reading operations you must use the synchronous api or SerialInputStream/SerialOutputStream