使用Java编写串口程序的流程步骤

  import gnu.io.*;

  public class SerialPortExample implements SerialPortEventListener {

  private SerialPort serialPort;

  public SerialPortExample() {

  try {

  String portName = "/dev/ttyUSB0"; // 串口名称

  int baudRate = 9600; // 波特率

  CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);

  serialPort = (SerialPort) portIdentifier.open("SerialPortExample", 2000);

  serialPort.addEventListener(this);

  serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

  serialPort.notifyOnDataAvailable(true);

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  public void serialEvent(SerialPortEvent event) {

  if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {

  try {

  byte[] buffer = new byte[1024];

  int len = serialPort.getInputStream().read(buffer);

  // 处理接收到的数据

  String data = new String(buffer, 0, len);

  System.out.println("Received data: " + data);

  } catch (Exception e) {

  e.printStackTrace();

  }

  }

  }

  public static void main(String[] args) {

  new SerialPortExample();

  }

  }