Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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(57600,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("Error: Only serial ports are handled by this example.");
- }
- }
- }
- /**
- * Handles the input coming from the serial port. A new line character
- * is treated as the end of a block in this example.
- */
- public static class SerialReader implements SerialPortEventListener
- {
- Scanner scanner;
- private InputStream in;
- private byte[] buffer = new byte[1024];
- public SerialReader ( InputStream in )
- {
- this.in = in;
- this.scanner = new Scanner(in);
- }
- public void serialEvent(SerialPortEvent event) {
- int data;
- StringBuilder value = new StringBuilder();
- if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
- try
- {
- int len = 0;
- while ( ( data = in.read()) > -1 )
- {
- if ( data == 'n' ) {
- break;
- }
- buffer[len++] = (byte) data;
- }
- String s = new String(buffer,0,len);
- // String s = new String(buffer, Charset.forName("UTF-32"));
- }
- catch ( IOException e )
- {
- e.printStackTrace();
- System.exit(-1);
- }
- }
- }
- }
- /** */
- public static class SerialWriter implements Runnable
- {
- OutputStream out;
- public SerialWriter ( OutputStream out )
- {
- this.out = out;
- }
- public void run ()
- {
- try
- {
- int c = 0;
- while ( ( c = System.in.read()) > -1 )
- {
- this.out.write(c);
- }
- }
- 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();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement