设置串口波特率(有些串口是需要设置才能输出读取)
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();
}
}
}