Java でシリアル通信を行う方法

RXTXライブラリを使用するとJavaでシリアル通信を行うことができます。その簡単なサンプルコードを以下に示します。

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.InputStream;
import java.io.OutputStream;

public class SerialCommunication {
    public static void main(String[] args) {
        try {
            // 获取串口标识符
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1");

            // 打开串口并设置通信参数
            CommPort commPort = portIdentifier.open("SerialCommunication", 2000);
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            // 获取输入流和输出流
            InputStream inputStream = serialPort.getInputStream();
            OutputStream outputStream = serialPort.getOutputStream();

            // 向串口发送数据
            outputStream.write("Hello World".getBytes());

            // 从串口读取数据
            byte[] buffer = new byte[1024];
            int len = inputStream.read(buffer);
            String receivedData = new String(buffer, 0, len);
            System.out.println("Received data: " + receivedData);

            // 关闭串口
            serialPort.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上記コードでは、まずシリアル識別子をゲットし、次にシリアルを開き、通信パラメーターを設定します。次に、入力および出力ストリームをゲットしてデータの読み書きを行います。最後にシリアルを閉じます。この時、RXTXライブラリをインポートする必要があり、シリアル名称および通信パラメーターを実際の設定に従って変更する必要があります。

bannerAds