如何在java中使用jssc从串行端口读取数据? [英] how to read data frome serialport using jssc in java?

查看:104
本文介绍了如何在java中使用jssc从串行端口读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 jssc 库从串口读取和写入数据.

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.

推荐答案

发生的事情是您正在关闭端口:serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);

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

        serialPort.writeString("S");

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

这篇关于如何在java中使用jssc从串行端口读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆