Java实现的串口通信功能示例
本文实例讲述了Java实现的串口通信功能。分享给大家供大家参考,具体如下:
用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”,控制显示器则发送一次重量数据给串口,计算机再读取将数据显示在网页上。这样就构成了一个实时称重系统。
读写串口的代码如下:
packagecom.chengzhong.tools;
importjava.io.*;
importjavax.comm.CommPortIdentifier;
importjavax.comm.*;
/**
*
*Thisbeanprovidessomebasicfunctionstoimplementfullduplex
*informationexchangethroughtheserialport.
*
*/
publicclassSerialBean
{
publicstaticStringPortName;
publicstaticCommPortIdentifierportId;
publicstaticSerialPortserialPort;
publicstaticOutputStreamout;
publicstaticInputStreamin;
//保存读数结果
publicstaticStringresult="";
publicstaticintopenSignal=1;
/**
*
*Constructor
*
*@paramPortIDtheIDoftheserialtobeused.1forCOM1,
*2forCOM2,etc.
*
*/
publicSerialBean(intPortID)
{
PortName="COM"+PortID;
}
/**
*
*Thisfunctioninitializetheserialportforcommunication.Itstartsa
*threadwhichconsistentlymonitorstheserialport.Anysignalcaptured
*fromtheserialportisstoredintoabufferarea.
*
*/
publicintInitialize()
{
openSignal=1;
try
{
portId=CommPortIdentifier.getPortIdentifier(PortName);
try
{
serialPort=(SerialPort)
portId.open("Serial_Communication",2000);
}catch(PortInUseExceptione)
{
if(!SerialBean.portId.getCurrentOwner().equals("Serial_Communication"))
{
openSignal=2;//该串口被其它程序占用
}elseif(SerialBean.portId.getCurrentOwner().equals("Serial_Communication")){
openSignal=1;
returnopenSignal;
}
returnopenSignal;
}
//UseInputStreamintoreadfromtheserialport,andOutputStream
//outtowritetotheserialport.
try
{
in=serialPort.getInputStream();
out=serialPort.getOutputStream();
}catch(IOExceptione)
{
openSignal=3;//输入输出流错误
returnopenSignal;
}
//Initializethecommunicationparametersto9600,8,1,none.
try
{
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
}catch(UnsupportedCommOperationExceptione)
{
openSignal=4;//参数不正确
returnopenSignal;
}
}catch(NoSuchPortExceptione)
{
portId=null;
openSignal=5;//没有该串口
returnopenSignal;
}
//whensuccessfullyopentheserialport,createanewserialbuffer,
//thencreateathreadthatconsistentlyacceptsincomingsignalsfrom
//theserialport.Incomingsignalsarestoredintheserialbuffer.
//returnsuccessinformation
returnopenSignal;
}
/**
*
*Thisfunctionreturnsastringwithacertainlengthfromtheincoming
*messages.
*
*@paramLengthThelengthofthestringtobereturned.
*
*/
publicstaticvoidReadPort()
{
SerialBean.result="";
intc;
try{
if(in!=null){
while(in.available()>0)
{
c=in.read();
Characterd=newCharacter((char)c);
SerialBean.result=SerialBean.result.concat(d.toString());
}
}
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
/**
*
*Thisfunctionsendsamessagethroughtheserialport.
*
*@paramMsgThestringtobesent.
*
*/
publicstaticvoidWritePort(StringMsg)
{
try
{
if(out!=null){
for(inti=0;i
这样通过SerialBean.result就可得到读数结果。
至于把数据放到网页上,就要用到Ajax了,这里用到了一个Ajax框架dwr,dwr类Put.java如下:
packagecom.chengzhong.dwr;
importjava.io.IOException;
importcom.chengzhong.tools.Arith;
importcom.chengzhong.tools.SerialBean;
publicclassPut{
//2011.9.17
publicStringwrite(){
//发送指令R,仪器发送一次净重数据
SerialBean.WritePort("R");
//读取数据
SerialBean.ReadPort();
Stringtemp=SerialBean.result.trim();//我这里temp是形如wn125.000kg的数据
if(!temp.equals("")&&temp.length()==11)
{
return(change(temp)).toString();
}else{
return"";
}
}
//响应开始称重
publicStringstartWeight(Stringnum){
intn=Integer.parseInt(num.trim());
SerialBeanSB=newSerialBean(n);
SB.Initialize();
returnSerialBean.openSignal+"";//返回初始化信息
}
//响应停止称重
publicvoidendWeight(){
try{
//关闭输入、输出流
SerialBean.in.close();
SerialBean.out.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
if(SerialBean.serialPort!=null){
SerialBean.serialPort.close();//关闭串口
}
SerialBean.serialPort=null;
SerialBean.portId=null;
SerialBean.result="";
}
/**
*将形如wn125.000kg格式的重量转换为125.000(kg)(四舍五入,小数点后保留两位)
*/
publicStringchange(Stringsource){
Doubleresult=0.0;
Strings1=source.substring(2,9);
try{
result=Double.parseDouble(s1);
result=Arith.round(result,2);
}catch(Exceptione){
e.printStackTrace();
return"";
}
returnresult.toString();
}
}
注:Arith.java是一个java的高精度计算文件。
packagecom.chengzhong.tools;
importjava.math.BigDecimal;
/**
*由于Java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精
*确的浮点数运算,包括加减乘除和四舍五入。
*/
publicclassArith{
//默认除法运算精度
privatestaticfinalintDEF_DIV_SCALE=10;
//这个类不能实例化
privateArith(){
}
/**
*提供精确的加法运算。
*@paramv1被加数
*@paramv2加数
*@return两个参数的和
*/
publicstaticdoubleadd(doublev1,doublev2){
BigDecimalb1=newBigDecimal(Double.toString(v1));
BigDecimalb2=newBigDecimal(Double.toString(v2));
returnb1.add(b2).doubleValue();
}
/**
*提供精确的减法运算。
*@paramv1被减数
*@paramv2减数
*@return两个参数的差
*/
publicstaticdoublesub(doublev1,doublev2){
BigDecimalb1=newBigDecimal(Double.toString(v1));
BigDecimalb2=newBigDecimal(Double.toString(v2));
returnb1.subtract(b2).doubleValue();
}
/**
*提供精确的乘法运算。
*@paramv1被乘数
*@paramv2乘数
*@return两个参数的积
*/
publicstaticdoublemul(doublev1,doublev2){
BigDecimalb1=newBigDecimal(Double.toString(v1));
BigDecimalb2=newBigDecimal(Double.toString(v2));
returnb1.multiply(b2).doubleValue();
}
/**
*提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
*小数点以后10位,以后的数字四舍五入。
*@paramv1被除数
*@paramv2除数
*@return两个参数的商
*/
publicstaticdoublediv(doublev1,doublev2){
returndiv(v1,v2,DEF_DIV_SCALE);
}
/**
*提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
*定精度,以后的数字四舍五入。
*@paramv1被除数
*@paramv2除数
*@paramscale表示表示需要精确到小数点以后几位。
*@return两个参数的商
*/
publicstaticdoublediv(doublev1,doublev2,intscale){
if(scale<0){
thrownewIllegalArgumentException(
"Thescalemustbeapositiveintegerorzero");
}
BigDecimalb1=newBigDecimal(Double.toString(v1));
BigDecimalb2=newBigDecimal(Double.toString(v2));
returnb1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
*提供精确的小数位四舍五入处理。
*@paramv需要四舍五入的数字
*@paramscale小数点后保留几位
*@return四舍五入后的结果
*/
publicstaticdoubleround(doublev,intscale){
if(scale<0){
thrownewIllegalArgumentException(
"Thescalemustbeapositiveintegerorzero");
}
BigDecimalb=newBigDecimal(Double.toString(v));
BigDecimalone=newBigDecimal("1");
returnb.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
网页页面上:
varID;
functionbegin(){
ID=window.setInterval('get()',500);//每隔半秒自动调用get(),取得毛重数据填入文本框中
}
functionget()
{
ss.write(readIt);//调用dwr类Put.java中的write方法
}
functionreadIt(Data){
if(Data!=null&&Data!="")
{
document.getElementById("mzBF").value=Data;
}
}
dwr的使用就不说了
更多关于java相关内容感兴趣的读者可查看本站专题:《JavaSocket编程技巧总结》、《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。