java 串口通信實現(xiàn)流程示例
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:通過它可以直接對串口進行讀、寫及設(shè)置工作
5、列出本機可用端口
Enumeration<CommPortIdentifier> em = CommPortIdentifier.getPortIdentifiers();
while (em.hasMoreElements()) {
String name = em.nextElement().getName();
System.out.println(name);
}
6、一般步驟:打開串口得到串口對象==》設(shè)置參數(shù)==》對串口進行讀寫==》關(guān)閉串口,其中對串口進行讀操作比較常用
//打開串口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM4");//COM4是串口名字
CommPort commPort = portIdentifier.open("COM4", 2000); //2000是打開超時時間
serialPort = (SerialPort) commPort;
//設(shè)置參數(shù)(包括波特率,輸入/輸出流控制,數(shù)據(jù)位數(shù),停止位和齊偶校驗)
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//監(jiān)聽串口事件
serialPort.addEventListener(new Abc()); //Abc是實現(xiàn)SerialPortEventListener接口的類,具體讀操作在里面進行
// 設(shè)置當有數(shù)據(jù)到達時喚醒監(jiān)聽接收線程
serialPort.notifyOnDataAvailable(true);
// 設(shè)置當通信中斷時喚醒中斷線程
serialPort.notifyOnBreakInterrupt(true);
// in.close(); //關(guān)閉串口
Abc類內(nèi)容,即讀串口的具體操作:
public class Abc implements SerialPortEventListener {
public void serialEvent(SerialPortEvent arg0) {
// TODO Auto-generated method stub
//對以下內(nèi)容進行判斷并操作
/*
BI -通訊中斷
CD -載波檢測
CTS -清除發(fā)送
DATA_AVAILABLE -有數(shù)據(jù)到達
DSR -數(shù)據(jù)設(shè)備準備好
FE -幀錯誤
OE -溢位錯誤
OUTPUT_BUFFER_EMPTY -輸出緩沖區(qū)已清空
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數(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();
}
}
}
}
寫操作:
OutputStream out = serialPort.getOutputStream(); out.write(data); //byte[] data; out.flush();
總結(jié)
以上就是本文關(guān)于java 串口通信實現(xiàn)流程示例的全部內(nèi)容,希望對大家有所幫助。如有問題可以隨時留言,期待您的寶貴意見。
相關(guān)文章
Java?Rabbitmq中四種集群架構(gòu)的區(qū)別詳解
這篇文章主要為大家詳細介紹了Java?Rabbitmq中四種集群架構(gòu)的區(qū)別,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
MyBatis-Plus:saveOrUpdate根據(jù)指定字段更新或插入方式
這篇文章主要介紹了MyBatis-Plus:saveOrUpdate根據(jù)指定字段更新或插入方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
詳解如何配置springboot跳轉(zhuǎn)html頁面
這篇文章主要介紹了詳解如何配置springboot跳轉(zhuǎn)html頁面,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09
Springmvc獲取前臺請求數(shù)據(jù)過程解析
這篇文章主要介紹了Springmvc獲取前臺請求數(shù)據(jù)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07
詳解Java中NullPointerException的處理方法
這篇文章將帶大家來單獨看一個很常見的異常--空指針異常,這個可以說是每個Java程序員都必知的異常,所以我們不得不單獨學習一下,文中有詳細的代碼示例,需要的朋友可以參考下2023-08-08

