1、下載64位rxtx for java 鏈接:http://fizzed.com/oss/rxtx-for-java
2、下載下來的包解壓后按照說明放到JAVA_HOME即JAVA的安裝路徑下面去
3、在maven的pom.xml下添加
1
2
3
4
5
|
< dependency > < groupId >org.rxtx</ groupId > < artifactId >rxtx</ artifactId > < version >2.1.7</ version > </ dependency > |
4、串口API
CommPort:端口的抽象類
CommPortIdentifier:對串口訪問和控制的核心類
SerialPort:通過它可以直接對串口進行讀、寫及設置工作
5、列出本機可用端口
1
2
3
4
5
|
Enumeration<CommPortIdentifier> em = CommPortIdentifier.getPortIdentifiers(); while (em.hasMoreElements()) { String name = em.nextElement().getName(); System.out.println(name); } |
6、一般步驟:打開串口得到串口對象==》設置參數==》對串口進行讀寫==》關閉串口,其中對串口進行讀操作比較常用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//打開串口 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類內容,即讀串口的具體操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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(); } } } } |
寫操作:
1
2
3
|
OutputStream out = serialPort.getOutputStream(); out.write(data); //byte[] data; out.flush(); |
總結
以上就是本文關于java 串口通信實現流程示例的全部內容,希望對大家有所幫助。如有問題可以隨時留言,期待您的寶貴意見。
原文鏈接:http://www.cnblogs.com/zhylioooo/p/7886189.html