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:通過它可以直接對串口進(jìn)行讀、寫及設(shè)置工作
5、列出本機(jī)可用端口
1
2
3
4
5
|
Enumeration<CommPortIdentifier> em = CommPortIdentifier.getPortIdentifiers(); while (em.hasMoreElements()) { String name = em.nextElement().getName(); System.out.println(name); } |
6、一般步驟:打開串口得到串口對象==》設(shè)置參數(shù)==》對串口進(jìn)行讀寫==》關(guān)閉串口,其中對串口進(jìn)行讀操作比較常用
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是打開超時(shí)時(shí)間 serialPort = (SerialPort) commPort; //設(shè)置參數(shù)(包括波特率,輸入/輸出流控制,數(shù)據(jù)位數(shù),停止位和齊偶校驗(yàn)) serialPort.setSerialPortParams( 9600 , SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); //監(jiān)聽串口事件 serialPort.addEventListener( new Abc()); //Abc是實(shí)現(xiàn)SerialPortEventListener接口的類,具體讀操作在里面進(jìn)行 // 設(shè)置當(dāng)有數(shù)據(jù)到達(dá)時(shí)喚醒監(jiān)聽接收線程 serialPort.notifyOnDataAvailable( true ); // 設(shè)置當(dāng)通信中斷時(shí)喚醒中斷線程 serialPort.notifyOnBreakInterrupt( true ); // in.close(); //關(guān)閉串口 |
Abc類內(nèi)容,即讀串口的具體操作:
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 //對以下內(nèi)容進(jìn)行判斷并操作 /* BI -通訊中斷 CD -載波檢測 CTS -清除發(fā)送 DATA_AVAILABLE -有數(shù)據(jù)到達(dá) DSR -數(shù)據(jù)設(shè)備準(zhǔn)備好 FE -幀錯(cuò)誤 OE -溢位錯(cuò)誤 OUTPUT_BUFFER_EMPTY -輸出緩沖區(qū)已清空 PE -奇偶校驗(yàn)錯(cuò) RI - 振鈴指示 */ //switch多個(gè),if單個(gè) 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數(shù)組為buffer中數(shù)據(jù)的長度 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(); |
總結(jié)
以上就是本文關(guān)于java 串口通信實(shí)現(xiàn)流程示例的全部內(nèi)容,希望對大家有所幫助。如有問題可以隨時(shí)留言,期待您的寶貴意見。
原文鏈接:http://www.cnblogs.com/zhylioooo/p/7886189.html