新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

如何使用Java实现串口通信,java中如何使用π

发布时间:2023-10-22 10:11:11

如何使用Java实现串口通讯

要使用Java实现串口通讯,可使用Java的RXTX库。以下是一个简单的示例代码:

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库,并根据实际情况修改串口名称和通讯参数。