学无先后,达者为师

网站首页 编程语言 正文

linux设置串口波特率和读取

作者:小徐敲java 更新时间: 2024-04-04 编程语言

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

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

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新