另外一篇文章的源代碼:https://github.com/shmll/SerialPortDemo
本篇原文:https://blog.csdn.net/songyulong8888/article/details/78234275?utm_source=blogxgwz3
RXTXcomm:提供了 Windows x64, x86, ia64 and Linux x86, x86_64等操作系統支持。
下載地址 http://fizzed.com/oss/rxtx-for-java
使用RXTXcomm首先要安排JRE環境,開發IED可能eclipse.
1.下載系統相應的RXTXcomm。
2.將rxtxSerial.dll、rxtxParallel.dll復制到\jre\bin目錄下。
將RXTXcomm.jar復制到\jre\lib\ext目錄下。
可能還需要把rxtxParallel.dll、rxtxSerial.dll拷貝到:C:\WINDOWS\system32下。
API概述
接口
CommDriver 可負載設備(the loadable device)驅動程序接口的一部分
CommPortOwnershipListener 傳遞各種通訊端口的所有權事件
ParallelPortEventListener 傳遞並行端口事件
SerialPortEventListener 傳遞串行端口事件
類
CommPort 通訊端口 CommDriver 可負載設備(the loadable device)驅動程序接口的一部分
CommPortOwnershipListener 傳遞各種通訊端口的所有權事件
ParallelPortEventListener 傳遞並行端口事件
SerialPortEventListener 傳遞串行端口事件
SerialPortEvent 異常類
NoSuchPortException 當驅動程序不能找到指定端口時拋出
PortInUseException 當碰到指定端口正在使用中時拋出
UnsupportedCommOperationException 驅動程序不允許指定操作時拋出
重要類詳述
CommPort類
描述被底層系統支持的端口的抽象類。包含一些高層的IO控制方法,這些方法對於所有不同的通訊端口來說是通用的。SerialPort(串口) 和ParallelPort(並口)都是它的子類。
CommPortIdentifier
主要用於對串口進行管理和設置,是對串口進行訪問控制的核心類。主要方法如下:
[java] view plain copy
addPortName(String, int, CommDriver) 添加端口名到端口列表里
addPortOwnershipListener(CommPortOwnershipListener) 添加端口擁有的監聽器
removePortOwnershipListener(CommPortOwnershipListener) 移除端口擁有的監聽器
getCurrentOwner() 得到當前占有端口的對象或應用程序
getName() 得到端口名稱
getPortIdentifier(CommPort) 得到參數打開的端口的CommPortIdentifier類型對象
getPortIdentifier(String) 得到以參數命名的端口的CommPortIdentifier類型對象
getPortIdentifiers() 得到系統中的端口列表
getPortType() 得到端口的類型
isCurrentlyOwned() 判斷當前端口是否被占用
open(FileDescriptor) 用文件描述的類型打開端口
open(String, int) 打開端口,兩個參數:程序名稱,延遲時間(毫秒數)
SerialPort 串口參數的函數
getBaudRate() 得到波特率
getParity() 得到檢驗類型
getDataBits() 得到數據位數
getStopBits() 得到停止位數
setSerialPortParams(int, int, int, int) 設置串口參數依次為(波特率,數據位,停止位,奇偶檢驗)
close() 關閉串口
getOutputStream() 得到OutputStream類型的輸出流
getInputStream() 得到InputStream類型的輸入流
事件及事件方法
isCD() 是否有載波
isCTS() 是否清除發送
isDSR() 數據是否准備就緒
isDTR() 數據終端是否准備就緒
isRI() 是否響鈴偵測
isRTS() 是否要求發送
addEventListener(SerialPortEventListener) 向SerialPort對象中添加串口事件監聽器
removeEventListener() 移除SerialPort對象中的串口事件監聽器
getEventType() 得到發生的事件類型返回值為int型
sendBreak(int) 設置中斷過程的時間,參數為毫秒值
setRTS(boolean) 設置或清除RTS位
setDTR(boolean) 設置或清除DTR位
notifyOnBreakInterrupt(boolean) 設置中斷事件
notifyOnCarrierDetect(boolean) 設置載波監聽事件
notifyOnCTS(boolean) 設置清除發送事件
notifyOnDataAvailable(boolean) 設置串口有數據的事件
notifyOnDSR(boolean) 設置數據備妥事件
notifyOnFramingError(boolean) 設置發生錯誤事件
notifyOnOutputEmpty(boolean) 設置發送緩沖區為空事件
notifyOnParityError(boolean) 設置發生奇偶檢驗錯誤事件
notifyOnRingIndicator(boolean) 設置響鈴偵測事件
串口參數的靜態成員變量
成員變量 說明 成員變量 說明 成員變量 說明
DATABITS_5 數據位為5 STOPBITS_2 停止位為2 PARITY_ODD 奇檢驗
DATABITS_6 數據位為6 STOPBITS_1 停止位為1 PARITY_MARK 標記檢驗
DATABITS_7 數據位為7 STOPBITS_1_5 停止為1.5 PARITY_NONE 空格檢驗
DATABITS_8 數據位為8 PARITY_EVEN 偶檢驗 PARITY_SPACE 無檢驗
代碼實例:
package javaCOM; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.Buffer; import java.util.Enumeration; import java.util.TooManyListenersException; import com.sun.org.apache.bcel.internal.generic.NEW; import gnu.io.CommDriver; import gnu.io.CommPortIdentifier; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; import javafx.scene.chart.PieChart.Data; //import com.apple.dnssd.*; //import com.sun.org.apache.bcel.internal.generic.I2C; //import com.sun.org.apache.bcel.internal.generic.NEW; /** * Created by gbr on 13-12-11. */ public class ReadCom implements SerialPortEventListener { //枚舉類型 Enumeration<CommPortIdentifier> portList; // 檢測系統可用端口 private CommPortIdentifier portIdentifier; // 端口 private SerialPort port; // 輸入/輸出流 private InputStream inputStream; private OutputStream outputStream; public void getPortList() { // 獲得系統支持的所有端口(串口,並口) portList = CommPortIdentifier.getPortIdentifiers(); while(portList.hasMoreElements()) { portIdentifier = (CommPortIdentifier)portList.nextElement(); // CommPortIdentifier.PORT_SERIAL :串口 // CommPortIdentifier.PORT_PARALLEL :並口 // CommPortIdentifier.PORT_RS485 :RS485 // CommPortIdentifier.PORT_I2C :I2C // CommPortIdentifier.PORT_RAW if (portIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { System.out.println(portIdentifier.getName()); if (portIdentifier.getName().equals("COM3")) { try { // open:打開串口,第一個參數應用程序名稱 字符串可隨意填寫,第二個參數阻塞時等待多少毫秒 port = (SerialPort)portIdentifier.open("ReadCom888", 2000); // 串口設置監聽 port.addEventListener(this); // 設置可監聽 port.notifyOnDataAvailable(true); // 設置串口通信參數 // 波特率,數據位,停止位,校驗方式 port.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); outputStream = port.getOutputStream(); inputStream = port.getInputStream(); } catch (PortInUseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TooManyListenersException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedCommOperationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } @Override public void serialEvent(SerialPortEvent event) { // TODO Auto-generated method stub // TODO Auto-generated method stub /* * SerialPortEvent.BI:/*Break interrupt,通訊中斷 * SerialPortEvent.OE:/*Overrun error,溢位錯誤 * SerialPortEvent.FE:/*Framing error,傳幀錯誤 * SerialPortEvent.PE:/*Parity error,校驗錯誤 * SerialPortEvent.CD:/*Carrier detect,載波檢測 * SerialPortEvent.CTS:/*Clear to send,清除發送 * SerialPortEvent.DSR:/*Data set ready,數據設備就緒 * SerialPortEvent.RI:/*Ring indicator,響鈴指示 * SerialPortEvent.OUTPUT_BUFFER_EMPTY:/*Output buffer is empty,輸出緩沖區清空 * SerialPortEvent.DATA_AVAILABLE: */ switch (event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: // readData(); break; default: break; } } public void readData() { byte[] rbuff = new byte[1024]; int hasRead = 0; try { while((hasRead=inputStream.read(rbuff)) > 0) { System.out.print(new String(rbuff, 0, hasRead)); break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void sendData(String data) { try { outputStream.write(data.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { new ReadCom().getPortList(); } }
運行錯誤:
gnu.io.PortInUseException: Unknown Application:串口端口被占用
一般關掉占用端口的應用即可。