近期要做一個運行與安卓系統之上,與檢測儀器進行串口通訊的軟體,折騰了好幾天,現在整理了一個串口通訊的完整例子,引用的是RXTX相關的包:
類結構:
SPComm.java: 通訊主體
SPCommTest.java: 調用者
1. SPComm.java
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 java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.TooManyListenersException;public class SPComm implements Runnable, SerialPortEventListener {// 檢測系統中可用的通訊連接埠類private static CommPortIdentifier portId;private static Enumeration<CommPortIdentifier> portList;// 輸入輸出資料流public static InputStream inputStream;public static OutputStream outputStream;// RS-232的串列口public static SerialPort serialPort;public static Thread commThread;//初始化串口public static void init() {portList = CommPortIdentifier.getPortIdentifiers();while (portList.hasMoreElements()) {portId = (CommPortIdentifier) portList.nextElement();if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){if (portId.getName().equals("COM8")) {try {serialPort = (SerialPort) portId.open("SerialPort-Test", 2000);serialPort.addEventListener(new SPComm());serialPort.notifyOnDataAvailable(true);/* 設定串口通訊參數 */serialPort.setSerialPortParams(19200,SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);outputStream = serialPort.getOutputStream();inputStream = serialPort.getInputStream();} catch (PortInUseException e) {e.printStackTrace();} catch (TooManyListenersException e) {e.printStackTrace();} catch (UnsupportedCommOperationException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} }}}}/** * 實現介面SerialPortEventListener中的方法 讀取從串口中接收的資料 */public void serialEvent(SerialPortEvent event) {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://擷取到串口返回資訊 int newData = 0; int i = 0; do{try{newData = inputStream.read();//對資料進行處理,省略...i++;if(i == 24){ //根據實際需求,在適當的時候設定結束條件newData = -1;}}catch(IOException e){return;}}while(newData != -1); serialPort.close();//這裡一定要用close()方法關閉串口,釋放資源 break;default:break;}}//向串口發送資訊方法public static void sendMsg(){String msg = "xxxxxxxxxxxxxx";//要發送的命令try { outputStream.write(hexStringToBytes(msg));} catch (IOException e) {e.printStackTrace();}}public void run(){ init(); sendMsg(); }}
2. SPCommTest.java
public class SPCommTest {public static void main(String[] args){Thread spcommThread = new Thread(new SPComm());spcommThread.setName("Thread-MyThread");spcommThread.start();}}
運行SPComm.java即可。