用Java实现串口通信(windows系统下),需要用到sun提供的串口包 javacomm20-win32.zip。其中要用到三个文件,配置如下:
1.comm.jar放置到 JAVA_HOME/jre/lib/ext;
2.win32com.dll放置到 JAVA_HOME/bin;
3.javax.comm.properties 两个地方都要放
jre/lib(也就是在JAVA文件夹下的jre)
JAVA_HOME/jre/lib
说一下我应用的环境。电子秤称重时,计算机通过串口给称重控制显示器发送一次命令“R”,控制显示器则发送一次重量数据给串口,计算机再读取将数据显示在网页上。这样就构成了一个实时称重系统。
读写串口的代码如下:
package com.chengzhong.tools;
import java.io.;
import javax.comm.CommPortIdentifier;
import javax.comm.;
/**
*
* This bean provides some basic functions to implement full duplex
* information exchange through the serial port.
*
/
public class SerialBean
{
public static String PortName;
public static CommPortIdentifier portId;
public static SerialPort serialPort;
public static OutputStream out;
public static InputStream in;
//保存读数结果
public static String result="";
public static int openSignal=1;
/*
*
* Constructor
*
* @param PortID the ID of the serial to be used. 1 for COM1,
* 2 for COM2, etc.
*
/
public SerialBean(int PortID)
{
PortName = “COM” +PortID;
}
/*
*
* This function initialize the serial port for communication. It starts
a
* thread which consistently monitors the serial port. Any signal
captured
* from the serial port is stored into a buffer area.
*
/
public int Initialize()
{
openSignal=1;
try
{
portId = CommPortIdentifier.getPortIdentifier(PortName);
try
{
serialPort = (SerialPort)
portId.open(“Serial_Communication”, 2000);
} cat