在控制台上打印串行通讯

时间:2018-10-15 16:12:02

标签: java serial-port serial-communication

我正在尝试在Java程序中接收Arduino输出。我想我几乎可以正常使用了,但是它给出了一些重大错误。运行我的代码时,程序将显示Arduino发送的部分字符串。同时,它也给出了很多这样的内容:

com.fazecast.jSerialComm.SerialPortTimeoutException: The read operation timed out before any data was returned.

这些是我的课程:

package Serial;

    import com.fazecast.jSerialComm.SerialPort;
    import com.fazecast.jSerialComm.SerialPortDataListener;
    import com.fazecast.jSerialComm.SerialPortEvent;

    import java.io.*;

    public class SerialCom implements SerialPortDataListener {

        private SerialPort sp;

        private static final String portName = "COM3";
        private BufferedReader input;


        public void initialize() {

            SerialPort sp = SerialPort.getCommPort(portName);

            if (sp.openPort()) {
                System.out.println("Arduino - Connected");
            } else {
                System.out.println("Arduino - Missing");
                return;
            }

            try {
                // set port parameters
                sp.setComPortParameters(9600, 8, 1, 0);
                // open the streams
                input = new BufferedReader(new InputStreamReader(sp.getInputStream()));
                // add event listeners
                sp.addDataListener(this);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        public synchronized void close() {
            if (sp != null) {
                sp.removeDataListener();
                sp.closePort();
            }
        }


        public int getListeningEvents() {
            return sp.LISTENING_EVENT_DATA_AVAILABLE;
        }

        public synchronized void serialEvent(SerialPortEvent serialPortEvent) {
            if (serialPortEvent.getEventType() == sp.LISTENING_EVENT_DATA_AVAILABLE) {
                try {
                    String inputLine;
                    if (input.ready()) {
                        inputLine = input.readLine();
                        System.out.println(inputLine);
                    }

                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }
    }

主要:

package Main;

    import Serial.SerialCom;

    public class Main {
        public static void main(String [] args){

            SerialCom serialCom = new SerialCom();
            serialCom.initialize();
        }
    }

0 个答案:

没有答案