Open/close a serial port
The SerialPortManager allows you to create a SerialPort object for a specific port name. The listSerialPorts() method lists all the available serial ports in the device.
You can also specify other serial port parameters using a SerialPortParameters object or directly in the openSerialPort method.
Method |
Description |
---|---|
openSerialPort(String) |
Creates and opens a SerialPort object for the provided port name |
openSerialPort(String, SerialPortParameters) |
Creates and opens a SerialPort object for the provided port name with the given configuration |
openSerialPort(String, int, int, int, int, int, int) |
Creates and opens a SerialPort object for the provided port name with the given port parameters |
When they are not specified, the serial port parameter default values are the following:
- Baud rate: 9600
- Data bits: 8
- Stop bits: 1
- Parity: None
- Flow control: None
- Read timeout: 3 seconds
Note The SerialPort class includes constant definitions for the possible values of data bits, stop bits, parity, and flow control. For example: SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE, SerialPort.FLOWCONTROL_NONE.
The three methods that open the serial port may fail for the following reasons:
- If the serial port name is invalid or does not exist, the openSerialPort() method throws a NoSuchPortException.
- If the serial port is already in use by other application(s), the openSerialPort() method throws a PortInUseException.
Opening serial ports
import com.digi.android.serial.SerialPort; import com.digi.android.serial.SerialPortManager; import com.digi.android.serial.SerialPortParameters; [...] SerialPortManager serialPortManager = ...; // Get the list of available serial ports. String[] portNames = serialPortManager.listSerialPorts(); // Define a serial configuration: 115200/8/N/1 and hardware flow control. SerialPortParameters params = new SerialPortParameters( 9600, /* baudrate: 9600 */ SerialPort.DATABITS_8, /* data bits: 8 */ SerialPort.STOPBITS_1, /* stop bits: 1 */ SerialPort.PARITY_NONE, /* parity: none */ SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT, /* flow ctrl: hardware */ 2000 /* read timeout: 2s */); // Open the available serial ports with the previous configuration. SerialPorts[] ports = new SerialPorts[portNames.length]; for (int i = 0; i < portNames.length; i++) ports[i] = serialPortManager.openSerialPort(portNames[i], params); [...]
Once you have finished with a serial port, you must close it. This frees the port so that other applications can use it.
To close a serial port, use the close() method of the SerialPort object.
Closing serial ports
import com.digi.android.serial.SerialPort; import com.digi.android.serial.SerialPortManager; [...] SerialPortManager serialPortManager = ...; SerialPort port = ...; [...] // Close the serial port. port.close(); [...]