Skip to content

Instantly share code, notes, and snippets.

@dniklaus
Created September 14, 2022 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dniklaus/4e88a4540bf02897e875b131174d4a7d to your computer and use it in GitHub Desktop.
Save dniklaus/4e88a4540bf02897e875b131174d4a7d to your computer and use it in GitHub Desktop.
package dn;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
/**
* This version of the TwoWaySerialComm example makes use of the
* SerialPortEventListener to avoid polling.
*
* Source: http://www.javawenti.com/?post=91885
*/
public class TwoWaySerialComm
{
public TwoWaySerialComm()
{
super();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
// OutputStream out = serialPort.getOutputStream();
//
// (new Thread(new SerialWriter(out))).start();
serialPort.addEventListener(new SerialReader(in));
serialPort.notifyOnDataAvailable(true);
}
else
{
System.out.println("Not a serial port...");
}
}
}
public static class SerialReader implements SerialPortEventListener
{
private InputStream in;
private byte[] buffer = new byte[1024];
public SerialReader ( InputStream in )
{
this.in = in;
}
public void serialEvent(SerialPortEvent arg0) {
int data;
try
{
int len = 0;
while ( ( data = in.read()) > -1 )
{
if ( data == '\n' ) {
break;
}
buffer[len++] = (byte) data;
}
System.out.print("Result="+new String(buffer,0,len));
}
catch ( IOException e )
{
e.printStackTrace();
System.exit(-1);
}
}
}
public static void main ( String[] args )
{
try
{
(new TwoWaySerialComm()).connect("COM7");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment