简体   繁体   中英

Java Com port read write issue

In my application I am trying to write to a COM port. The connected device is an arduino that returns the message I send (for testing purposes). However when I write to it I don't get the response I expect but when I use a button in a GUI I do.

The write method:

public void write(String x) {
    try {
        outStream.write(x.getBytes());
        outStream.flush();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

The event listener

public void serialEvent(SerialPortEvent event) {
    logger.debug("listener called");
    if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        BufferedReader portReader = new BufferedReader(new InputStreamReader(inStream));
        try {
            String line = portReader.readLine();
            test(line);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

The serialport will notify if data is available and the listener is called after I write the data however I get an OUTPUT_BUFFER_EMPTY response while I expect the string I have sent.

The SerialPortHandler is based on instances so I can use the same one everywhere in my application.

example:

SerialPortHandler handler = SerialPortHandler.getInstance();
handler.write("hello world");

expected:

DEBUG [SerialPortHandler.java] - listener called
hello world

actual:

DEBUG [SerialPortHandler.java] - listener called

问题是我在写入和初始化serialportHandler的那一刻之间没有延迟

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM