how to read data frome serialport using jssc in java?

ぃ、小莉子 提交于 2021-02-19 06:39:06

问题


I used jssc library to read and write data from serial port.

package serial;

import jssc.*;

public class Serial {

public static void main(String[] args) {
    String[] portNames = null;
    portNames = SerialPortList.getPortNames();
    for (String string : portNames) {
        System.out.println(string);
    }

    if (portNames.length == 0) {
        System.out.println("There are no serial-ports");
    } else {

        SerialPort serialPort = new SerialPort("com2");
        try {
            serialPort.openPort();

            serialPort.setParams(SerialPort.BAUDRATE_9600,    SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT);

            PortReader portReader = new PortReader(serialPort);

            serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);

            serialPort.writeString("S");

            serialPort.closePort();
        } catch (Exception e) {
            System.out.println("There are an error on writing string to port т: " + e);
        }
    }
}
}

package serial;

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;

public class PortReader implements SerialPortEventListener {

SerialPort serialPort;
public PortReader(SerialPort serialPort) {
    this.serialPort = serialPort;
}

@Override
public void serialEvent(SerialPortEvent event) {
    System.out.println("started");
    if (event.isRXCHAR() && event.getEventValue() > 0) {
        try {
            String receivedData = serialPort.readString(event.getEventValue());
            System.out.println("Received response: " + receivedData);
        } catch (SerialPortException ex) {
            System.out.println("Error in receiving string from COM-port: " + ex);
        }
    }
}
}

I use virtual serial and port this code writes data to serial port.and I'm sure data are writing on serial port correctly.

but I can't read data from serial port.


回答1:


What happened is that you are closing port: serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);

        serialPort.writeString("S");

        serialPort.closePort();  // <----- You are closing port here


来源:https://stackoverflow.com/questions/36951451/how-to-read-data-frome-serialport-using-jssc-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!