Java 如何实现串口读写数据? - 知乎

Java通过使用javax.comm包提供了串口读写数据的API。以下是一个简单的示例代码:

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

public class SerialComm implements SerialPortEventListener {
    
    private SerialPort serialPort;
    
    public void connect(String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
            if (commPort instanceof SerialPort) {
                serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                InputStream in = serialPort.getInputStream();
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }
    
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
                String inputLine = reader.readLine();
                System.out.println("Received message: " + inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
    }
    
    public synchronized void writeData(String data) {
        if (serialPort != null) {
            try {
                OutputStream out = serialPort.getOutputStream();
                out.write(data.getBytes());
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
    }
    
    public static void main(String[] args) {
        try {
            SerialComm serialComm = new SerialComm();
            serialComm.connect("COM1");
            serialComm.writeData("Hello World");
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
    
}

上述示例代码中,connect()方法连接指定的串口,设置了串口的波特率、数据位、停止位和奇偶校验位等参数,并为串口设置了数据可用事件监听器;serialEvent()方法则处理数据可用事件,读取串口数据并输出到控制台;writeData()方法用于向串口写入数据。

注意,为了使用javax.comm包,需要下载并安装Java Communications API,并在项目中导入comm.jar文件。


原网址: 访问
创建于: 2023-11-22 10:06:08
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论