0

我是一个初学者的java开发人员。我从 com 端口读取时遇到问题。代码:

public class Main {

private static SerialPort serialPort;

public static void main(String[] args) {
    serialPort = new SerialPort("COM3");
    try {
        serialPort.openPort();
        Thread.sleep(2000);
        serialPort.setParams(SerialPort.BAUDRATE_57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
        serialPort.writeBytes("Test".getBytes());
        serialPort.setEventsMask(SerialPort.MASK_RXCHAR);
        serialPort.addEventListener(new EventListener());
    }
    catch (SerialPortException | InterruptedException ex) {
        System.out.println(ex);
    }
}

private static class EventListener implements SerialPortEventListener {

    public void serialEvent(SerialPortEvent event) {
        if(event.isRXCHAR() && event.getEventValue() == 8){
            try {
                byte[] buffer = serialPort.readBytes(8);
                for(int i = 0; i < buffer.length; i++){
                    System.out.println("Output" + buffer[i]);
                }
                serialPort.closePort();
            }
            catch (SerialPortException ex) {
                System.out.println(ex);
            }
        }
    }
}

没有显示任何内容,但我知道数据已写入。请帮忙。

4

1 回答 1

0

您用于通信/串行内容的库是什么?您可以在发送任何内容之前尝试添加serialPort.addEventListener(new EventListener());行,这可能是在侦听器映射之前发送了接收事件。

于 2020-06-11T18:08:21.433 回答