importgnu.io.*;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.OutputStream;publicclassSerialCommunicationExample{publicstaticvoidmain(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 instanceofSerialPort){SerialPort serialPort =(SerialPort) commPort;
serialPort.setSerialPortParams(baudRate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);// 读取串口信息BufferedReader reader =newBufferedReader(newInputStreamReader(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();}}}