linux设置串口波特率和读取

发布时间:2024年01月23日

设置串口波特率(有些串口是需要设置才能输出读取)

stty -F /dev/ttyUSB0 raw speed 9600

读取串口信息

cat /dev/ttyUSB0

java代码读取

import gnu.io.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class SerialCommunicationExample {
    public static void main(String[] args) {
        try {
            // 设置串口波特率
            String portName = "/dev/ttyUSB0"; // 串口设备名称
            int baudRate = 9600; // 波特率

            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            if (portIdentifier.isCurrentlyOwned()) {
                System.out.println("Error: Port is currently in use");
            } else {
                CommPort commPort = portIdentifier.open(SerialCommunicationExample.class.getName(), 2000);

                if (commPort instanceof SerialPort) {
                    SerialPort serialPort = (SerialPort) commPort;
                    serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                    // 读取串口信息
                    BufferedReader reader = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println("Received: " + line);
                    }

                    reader.close();
                    serialPort.close();
                } else {
                    System.out.println("Error: Only serial ports are handled by this example.");
                }
            }
        } catch (NoSuchPortException | PortInUseException | UnsupportedCommOperationException | IOException e) {
            e.printStackTrace();
        }
    }
}

文章来源:https://blog.csdn.net/qq_19891197/article/details/135768144
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。