Embedded Freaks..
August 13, 2008
Reading from serial port (using rxtx)
Once you’ve got the serial InputStream, reading would be easy. Here’s an example of code to read the serial port using InputStream:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| /** * Buffer to hold the reading */ private byte [] readBuffer = new byte [ 400 ]; private void readSerial() { try { int availableBytes = inStream.available(); if (availableBytes > 0 ) { // Read the serial port inStream.read(readBuffer, 0 , availableBytes); // Print it out System.out.println( new String(readBuffer, 0 , availableBytes)); } } catch (IOException e) { } } |
But the real problem comes from the place where you should place the code.
You can put inside the
You can put inside the
SerialPortEvent.DATA_AVAILABLE:
event, like this:
1
2
3
4
5
6
7
8
9
| private class SerialEventHandler implements SerialPortEventListener { public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) { case SerialPortEvent.DATA_AVAILABLE: readSerial(); break ; } } } |
Don’t forget to register the event handler, before you run the application
1
2
3
4
5
6
7
8
9
10
11
12
| /** * Set the serial event handler */ private void setSerialEventHandler(SerialPort serialPort) { try { // Add the serial port event listener serialPort.addEventListener( new SerialEventHandler()); serialPort.notifyOnDataAvailable( true ); } catch (TooManyListenersException ex) { System.err.println(ex.getMessage()); } } |
The result is the read procedure is only called when new data is accepted.
The other way to read the serial port data continously is by using other thread to read:
1
2
3
4
5
6
7
| private class ReadThread implements Runnable { public void run() { while ( true ) { readSerial(); } } } |
Here’s how you start the thread:
1
2
3
| public void setSerialListener() { new Thread( new ReadThread()).start(); } |
Conclusion
So, which one that is better, put the reading inside different thread or in the event handler ? Well..I don’t know about it yet. I’ll post it once I found the answer.
https://embeddedfreak.wordpress.com/2008/08/13/reading-from-serial-port-using-rxtx/
https://embeddedfreak.wordpress.com/2008/08/13/reading-from-serial-port-using-rxtx/