java串口通讯第一次使用,找的资料都比较麻烦,一时没有理出头绪,自己在示例的基础上整理了一个简单的应答示例,比较简陋,但演示了java串口通讯的基本过程。
package com.garfield.comm; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort; public class SimpleCommIO implements Runnable { static CommPortIdentifier portId;
static String cmdHand = "I\r\n";
static String cmdWeight = "WX\r\n";
static SerialPort serialPort;
static OutputStream outputStream;
static String comm="COM11"; InputStream inputStream;
Thread readThread; public void run() {
while (true) {
try {
byte[] readBuffer = new byte[200]; try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
System.out.print("收到数据:"+new String(readBuffer));
}
} catch (IOException e) {
e.printStackTrace();
}
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public void initComm() {
try{
portId = CommPortIdentifier.getPortIdentifier(comm);
serialPort = (SerialPort) portId.open("SimpleCommIO",2000); outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream(); serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}catch(Exception e){
e.printStackTrace();
} } public void writeComm(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args) { SimpleCommIO reader = new SimpleCommIO();
reader.initComm();
Thread readThread = new Thread(reader);
readThread.start();
System.out.println("发出指令:"+cmdHand);
reader.writeComm(cmdHand); //暂停一会儿
try {
Thread.sleep ( 2000 ) ;
} catch (InterruptedException ie)
{ }
System.out.println("发出指令:"+cmdWeight);
reader.writeComm(cmdWeight);
} }
另注配置:
将javacomm20-win32 .zip下载的文件解压缩后,在\javacomm20-win32\commapi目录下有必需的三个文件:
comm.jar,javax.comm. properties和win32comm.dll。
将文件comm.jar拷贝到%JAVA_HOME%\jre\lib\ext;
文件 javax.comm. properties拷贝到%JAVA_HOME%\jre\lib;
文件win32comm.dll拷贝到%JAVA_HOME%\bin。
注意%JAVA_HOME%是jdk的路径,而非jre。