- 論壇徽章:
- 0
|
本來可以用javax.comm這個包的,但是我機子上運行老是不成功,于是我換了rxtx包
javax.comm在windows下的開發(fā)維護已經(jīng)停止了,rxtx的舊版本支持在javax.comm-win32-2.0基礎(chǔ)上的擴展,rxtx新版本支持對javax.comm的覆蓋式支持,也就是說原來用javax.comm的把所有import javax.comm.*改成import gnu.io.*就可以正常使用了,其他只須相關(guān)的dll文件,不用properties文件,支持的端口類型也明顯多了很多
下載地址:
ftp://ftp.qbang.org/pub/rxtx/rxtx-2.1-7-bins-r2.zip
里面的然后配置環(huán)境
copy rxtxSerial.dll into your c:\program files\java\jre-version\bin dir
copy RXTXcomm.jar into your c:\program files\java\jre-version\lib\ext dir
把下載包中Windows\i368-mingw32\rxtxSerial.dll 放到你%java_home%\jre\bin下面
把下載包中RXTXcomm.jar放到%java_home%\jre\lib\ext下面
OK,可以寫程序了
/**
*
*/
package cn.zhongxiaogang.test;
import java.io.*;
import java.util.*;
import gnu.io.*;
public class SimpleRead implements SerialPortEventListener { //SerialPortEventListener 監(jiān)聽器,我的理解是獨立開辟一個線程監(jiān)聽串口數(shù)據(jù)
static CommPortIdentifier portId; //串口通信管理類
static Enumeration portList; //已經(jīng)連接上的端口的枚舉
InputStream inputStream; //從串口來的輸入流
OutputStream outputStream;//向串口輸出的流
SerialPort serialPort; //串口的引用
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("myApp", 2000);//打開串口名字為myapp,延遲為2毫秒
} catch (PortInUseException e) {
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
}
try {
serialPort.addEventListener(this); //給當(dāng)前串口天加一個監(jiān)聽器
} catch (TooManyListenersException e) {
}
serialPort.notifyOnDataAvailable(true); //當(dāng)有數(shù)據(jù)時通知
try {
serialPort.setSerialPortParams(2400, SerialPort.DATABITS_8, //設(shè)置串口讀寫參數(shù)
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
}
public void serialEvent(SerialPortEvent event) {//SerialPortEventListener 的方法,監(jiān)聽的時候會不斷執(zhí)行
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://當(dāng)有可用數(shù)據(jù)時讀取數(shù)據(jù),并且給串口返回數(shù)據(jù)
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
outputStream.write("xiaogang".getBytes());
System.out.println(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public static void main(String[] args) {
try {
portList = CommPortIdentifier.getPortIdentifiers(); //得到當(dāng)前連接上的端口
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {//判斷如果端口類型是串口
if (portId.getName().equals("COM3")) { //判斷如果COM3端口已經(jīng)啟動就連接
SimpleRead reader = new SimpleRead(); //實例一個
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
程序調(diào)試成功,不過還有很多問題,比如有亂碼,還有程序不面向?qū)ο?etc.
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u3/94064/showart_2144948.html |
|