从Com端口读取串行数据

时间:2017-11-02 08:33:22

标签: java serial-port serial-communication

我看到串行i / o操作存在很多问题所以我决定分享我的代码片段,其中我从带有RXTX库的串行端口读取串行数据。 当串口上有数据并打印出来时,该类读取等待。该类还将数据保存在一个名为data的String中,该数据可以从另一个类中获取

import java.io.*;
import java.util.*;
import javax.comm.*;

public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;

InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static String data = "";
public static String getData() {

    return data;
}

public static void setData(String data) {
    SimpleRead.data = data;
}




public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
             if (portId.getName().equals("COM1")) {
        //                if (portId.getName().equals("/dev/term/a")) {
                SimpleRead reader = new SimpleRead();
            }
        }
    }
}

public SimpleRead() {
    try {
        serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
    } catch (PortInUseException e) {System.out.println(e);}
    try {
        inputStream = serialPort.getInputStream();
    } catch (IOException e) {System.out.println(e);}
try {
        serialPort.addEventListener(this);
} catch (TooManyListenersException e) {System.out.println(e);}
    serialPort.notifyOnDataAvailable(true);
    try {
        serialPort.setSerialPortParams(9600,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {System.out.println(e);}
    readThread = new Thread(this);
    readThread.start();
}

public void run() {
    try {
        Thread.sleep(20000);
    } catch (InterruptedException e) {System.out.println(e);}
}

public void serialEvent(SerialPortEvent event) {
    switch(event.getEventType()) {
    case SerialPortEvent.BI:
    case SerialPortEvent.OE:
    case SerialPortEvent.FE:
    case SerialPortEvent.PE:
    case SerialPortEvent.CD:
    case SerialPortEvent.CTS:
    case SerialPortEvent.DSR:
    case SerialPortEvent.RI:
    case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
        break;
    case SerialPortEvent.DATA_AVAILABLE:
        byte[] readBuffer = new byte[20];
        String data1="";
        try {
            while (inputStream.available() > 0) {
                int numBytes = inputStream.read(readBuffer);
                data1=data1+(String) numBytes;
            }
            setData(data1)
            System.out.print(new String(readBuffer));
        } catch (IOException e) {System.out.println(e);}
        break;
    }
}
}

从串口到另一个类的读取数据的代码

  SimpleRead simpleRead=new SimpleRead;
  String finalData="";
  simpleRead.run();
  finalData=simpleRead.getData()

0 个答案:

没有答案