上海古都建筑设计集团,上海办公室装修设计公司,上海装修公司高质量的内容分享社区,上海装修公司我们不是内容生产者,我们只是上海办公室装修设计公司内容的搬运工平台

linux设置串口波特率和读取

guduadmin443月前

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

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();
        }
    }
}

网友评论

搜索
最新文章
热门文章
热门标签
 
 做梦梦见猫丢了  为什么总是做牙掉了的梦  婚姻算命生辰八字最准