最近在做zigbee的課程設計,需要Java實現對串口數據的讀寫操作。
網上找了很多代碼,好像都比較過時了,直接拿來用沒法跑通……QAQ……然后自己寫個教程留底,如有不當之處還請各位路過的大神賜教。
參考資料:http://www.docin.com/p-224301266.html
操作系統:64位Win7
java的串口API包:javax.comm在windows下的開法維護已經停止了,RXTX的舊版本支持在javax.comm-win32-2.0基礎上的擴展,RXTX新版本支持對javax.comm的覆蓋式支持,原來用javax.comm的把所有import javax.comm.*改成import gnu.io.*即可。
支持不同系統的RXTX包下載地址:http://mfizz.com/oss/rxtx-for-java
解壓后把mfz-rxtx-2.2-20081207-win-x64文件夾下的rxtxSerial.dll放到%JAVA_HOME%\jre\bin和C:\Windows\System32下面。
把RXTXcomm.jar放到%JAVA_HOME%\jre\lib\ext下面。
%JAVA_HOME%為你安裝JDK的路徑,我的是:C:\Program Files\Java\jdk1.7.0_45
開發環境我用的IntelliJ IDEA,Ctrl+Shift+alt+S,在Libraries中把RXTXcomm.jar包導入即可。
測試程序:查看PC上的串口
PS.因為我用的筆記本,所以讀出來的串口是COM8,一般的串口調試助手讀不到。推薦Access Port For Win7——一款功能強大的串口調試軟件。
下載地址:http://www.onlinedown.net/soft/119517.htm
import gnu.io.CommPortIdentifier; import java.util.Enumeration; /** * Created by gbr on 13-12-11. */ public class ReadCom { static Enumeration portList; static CommPortIdentifier portId; public static void main( String[] args ){ try{ portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()){ portId = (CommPortIdentifier)portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){ System.out.println(portId.getName()); } } }catch(Exception e){ e.printStackTrace(); } } }