java串口扩展包的配置介绍

java串口扩展包的配置介绍

1.下载

sun的官方下载 http://java.sun.com/products/javacomm/只提供solaris平台的x86/sparc架构及linux平台x86架构的扩展API,目前最新版本为3.0。

windows平台的扩展包到以下地址下载,http://llk.media.mit.edu/projects/cricket/software/javaSerial.zip(两个文件夹里面有所需的3个文件),http://mdubuc.freeshell.org/Jolt/javacomm20-win32.zip和(完整的2.0版本,还有examples)。

2.配置

将解压得到的三个文件分别放入以下位置,

javax.comm.properties--------> %JAVA_HOME%/jre/lib

comm.jar--------> %JAVA_HOME%/jre/lib/ext

win32com.dll--------> %JAVA_HOME%/jre/bin

3.测试

启动eclilpse 新建工程,导入samples/simple/文件夹中SimpleRead.java(添加一些代码,查看代码),将comm.jar添加到构建路径中,运行程序。

4.程序运行结果(在我机器上的效果)

port COM4
port COM6
port COM5
port LPT1
port LPT2

* 如果使用eclipse,需要设置<窗口>/<首选项>/<java>/<已安装的jre>为上述所说的jdk路径。

 

/*SimpleRead.java*/

import java.io.*;
import java.util.*;
import javax.comm.*;

public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;

InputStream inputStream;
SerialPort serialPort;
Thread readThread;

public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
System.out.println("port "+portId.getName());
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {

//if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
}
}
}

}

public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}

public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}

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:
byte[] readBuffer = new byte[20];

try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}