-
Notifications
You must be signed in to change notification settings - Fork 597
4. Asynchronous api
Remember to check the example module for a complete example
Now that we already have our UsbSerialDevice object this is what needs to be done in order to use the Asynchronous api
UsbSerialDevice serial = UsbSerialDevice.createUsbSerialDevice(device, usbConnection);
...
serial.open();
serial.setBaudRate(115200);
serial.setDataBits(UsbSerialInterface.DATA_BITS_8);
serial.setParity(UsbSerialInterface.PARITY_ODD);
serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
Flow control is also supported in CP210x and FTDI devices
/**
Values:
UsbSerialInterface.FLOW_CONTROL_OFF
UsbSerialInterface.FLOW_CONTROL_RTS_CTS
UsbSerialInterface.FLOW_CONTROL_DSR_DTR
**/
serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_RTS_CTS);
Reading from the serial port is performed through a callback. Note that this callback is not executed in the UI thread. That means you can't touch anything UI related here.
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(byte[] arg0)
{
// Code here :)
}
};
Pass a mCallback reference to the UsbSerialDevice object
serial.read(mCallback);
Now, write something
serial.write("DATA".getBytes());
You can also set RTS and DTR signals
serial.setRTS(true); // Raised
serial.setRTS(false); // Not Raised
serial.setDTR(true); // Raised
serial.setDTR(false); // Not Raised
Changes in the CTS and DSR lines will be received in the same manner. Define a callback and pass a reference of it.
private UsbSerialInterface.UsbCTSCallback ctsCallback = new UsbSerialInterface.UsbCTSCallback() {
@Override
public void onCTSChanged(boolean state) {
// Code here :)
}
};
private UsbSerialInterface.UsbDSRCallback dsrCallback = new UsbSerialInterface.UsbDSRCallback() {
@Override
public void onDSRChanged(boolean state) {
// Code here :)
}
};
serial.getCTS(ctsCallback);
//serial.getDSR(dsrCallback);
When you are done, close the device
serial.close();
300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600
Sometimes received information is split between calls. You can use ProtocolBuffer class for appending data
ProtocolBuffer buffer = new ProtocolBuffer(ProtocolBuffer.TEXT); //Also Binary
buffer.setDelimiter("\r\n");
...
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
@Override
public void onReceivedData(byte[] arg0)
{
buffer.appendData(arg0);
while(buffer.hasMoreCommands()){
String textCommand = buffer.nextTextCommand()
// Do your thing with textCommand
}
}
};