java 串口通信實現流程


1、下載64位rxtx for java 鏈接:http://fizzed.com/oss/rxtx-for-java

2、下載下來的包解壓后按照說明放到JAVA_HOME即JAVA的安裝路徑下面去

3、在maven的pom.xml下添加

    <dependency>
    <groupId>org.rxtx</groupId>
    <artifactId>rxtx</artifactId>
    <version>2.1.7</version>
  </dependency>

4、串口API

  CommPort:端口的抽象類
  CommPortIdentifier:對串口訪問和控制的核心類
  SerialPort:通過它可以直接對串口進行讀、寫及設置工作

5、列出本機可用端口

Enumeration<CommPortIdentifier> em = CommPortIdentifier.getPortIdentifiers();
  while (em.hasMoreElements()) {
    String name = em.nextElement().getName();
    System.out.println(name);
  }

6、一般步驟:打開串口得到串口對象==》設置參數==》對串口進行讀寫==》關閉串口,其中對串口進行讀操作比較常用

//打開串口
  CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM4");//COM4是串口名字
  CommPort commPort = portIdentifier.open("COM4", 2000);    //2000是打開超時時間
  serialPort = (SerialPort) commPort;
  //設置參數(包括波特率,輸入/輸出流控制,數據位數,停止位和齊偶校驗)
  serialPort.setSerialPortParams(9600,
  SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
  SerialPort.PARITY_NONE);
  //監聽串口事件
  serialPort.addEventListener(new Abc()); //Abc是實現SerialPortEventListener接口的類,具體讀操作在里面進行
  // 設置當有數據到達時喚醒監聽接收線程
  serialPort.notifyOnDataAvailable(true);
  // 設置當通信中斷時喚醒中斷線程
  serialPort.notifyOnBreakInterrupt(true);
  //    in.close(); //關閉串口

Abc類內容,即讀串口的具體操作:

public class Abc implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent arg0) {
        // TODO Auto-generated method stub
        //對以下內容進行判斷並操作
        /*
        BI -通訊中斷
      CD -載波檢測
      CTS -清除發送
      DATA_AVAILABLE -有數據到達
      DSR -數據設備准備好
      FE -幀錯誤
      OE -溢位錯誤
      OUTPUT_BUFFER_EMPTY -輸出緩沖區已清空
      PE -奇偶校驗錯
        RI - 振鈴指示
        */
        //switch多個,if單個
        if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                InputStream in = null;
                byte[] bytes = null;
                in = App.serialPort.getInputStream();

                int bufflenth = in.available();
                while (bufflenth != 0) {
                    // 初始化byte數組為buffer中數據的長度
                    bytes = new byte[bufflenth];
                    in.read(bytes);
                    System.out.println(new String(bytes));
                    bufflenth = in.available();
                }
                
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }    
}

寫操作:

OutputStream out = serialPort.getOutputStream();
out.write(data); //byte[] data;
out.flush();

7、打開關閉串口等動作要有觸發,異常要處理。—wxws

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM