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();
總結
以上就是本文關於java 串口通信實現流程示例的全部內容,希望對大家有所幫助。如有問題可以隨時留言,期待您的寶貴意見。