无法从串行端口

时间:2015-09-23 08:42:54

标签: java serial-port inputstream rxtx

我在从串口读取时遇到问题,我正在尝试下面的代码从串口读取和写入,我运行程序并在控制台中输入一些数据,然后我可以写入串口。我正在使用应用程序“Free Device Monitoring Studio”来观察串口的行为。但是当我运行我的程序时,它不会读取任何数据。这是我从link获得的程序:

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;
import java.io.OutputStream;

/**
 * This version of the TwoWaySerialComm example makes use of the
 * SerialPortEventListener to avoid polling.
 *
 */
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(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);


                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();
                InputStream in = serialPort.getInputStream();
     // serialPort.notifyOnDataAvailable(true);
                serialPort.addEventListener(new SerialReader(in));

                serialPort.notifyOnDataAvailable(true);

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }


       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((byte)c);
                    System.out.println((byte)c);
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }



    /**
     * 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
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            int data;

            try
            {
                data = in.read();
                int len = 0;
                while ( in.available()>0 )
                {
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.print("read"+new String(buffer,0,len));
            }
            catch ( IOException e )
            {
               System.out.println(e.getMessage());
               System.out.println("error");
               e.printStackTrace();
            }
        }

    }

    /** */




    public static void main ( String[] args )
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM5");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.print(e.toString());
        }
    }


}

我在serialEvent(SerialPortEvent arg0)方法的While循环中放置了一个断点,

 while ( ( data = in.read()) > -1 )

但它永远不会到达断点。并且它无法读取数据,因此它不会在控制台中使用此行写入内容:

System.out.print("read"+new String(buffer,0,len));

我需要一些帮助才能知道问题所在。

2 个答案:

答案 0 :(得分:0)

您不应该在事件处理程序中读取流的末尾。这是您应该循环while (in.available() > 0)的极少数情况之一。

编辑叹息。

int len = 0;
while (in.available() > 0)
{
    data = in.read();
    if ( data == -1 || data == '\n' ) {
        break;
    }
    buffer[len++] = (byte) data;
}

答案 1 :(得分:0)

我自己找到答案。我的错误是我通过串口向我的电路板发送了一些废话,当我发送了一些有意义的东西时它也是从串口读取的。