本文实例讲述了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”,控制显示器则发送一次重量数据给串口,计算机再读取将数据显示在网页上。这样就构成了一个实时称重系统。
读写串口的代码如下:
package com.chengzhong.tools;
import java.io.*;
import javax.comm.CommPortIdentifier;
import javax.comm.*;
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;
public SerialBean(int PortID)
{
PortName = "COM" +PortID;
}
public int Initialize()
{
openSignal=1;
try
{
portId = CommPortIdentifier.getPortIdentifier(PortName);
try
{
serialPort = (SerialPort)
portId.open("Serial_Communication", 2000);
} catch (PortInUseException e)
{
if(!SerialBean.portId.getCurrentOwner().equals("Serial_Communication"))
{
openSignal=2; //该串口被其它程序占用
}else if(SerialBean.portId.getCurrentOwner().equals("Serial_Communication")){
openSignal=1;
return openSignal;
}
return openSignal;
}
//Use InputStream in to read from the serial port, and OutputStream
//out to write to the serial port.
try
{
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} catch (IOException e)
{
openSignal=3; //输入输出流错误
return openSignal;
}
//Initialize the communication parameters to 9600, 8, 1, none.
try
{
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e)
{
openSignal=4; //参数不正确
return openSignal;
}
} catch (NoSuchPortException e)
{
portId=null;
openSignal=5; //没有该串口
return openSignal;
}
// when successfully open the serial port, create a new serial buffer,
// then create a thread that consistently accepts incoming signals from
// the serial port. Incoming signals are stored in the serial buffer.
// return success information
return openSignal;
}
public static void ReadPort()
{
SerialBean.result="";
int c;
try {
if(in!=null){
while(in.available()>0)
{
c = in.read();
Character d = new Character((char) c);
SerialBean.result=SerialBean.result.concat(d.toString());
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void WritePort(String Msg)
{
try
{
if(out!=null){
for (int i = 0; i < Msg.length(); i++)
out.write(Msg.charAt(i));
}
} catch (IOException e) {
return;
}
}
public void ClosePort()
{
serialPort.close();
}
}
这样通过 SerialBean.result 就可得到读数结果。
至于把数据放到网页上,就要用到Ajax了,这里用到了一个Ajax框架dwr, dwr类Put.java 如下:
package com.chengzhong.dwr;
import java.io.IOException;
import com.chengzhong.tools.Arith;
import com.chengzhong.tools.SerialBean;
public class Put {
//2011.9.17
public String write(){
//发送指令R,仪器发送一次净重数据
SerialBean.WritePort("R");
//读取数据
SerialBean.ReadPort();
String temp=SerialBean.result.trim(); //我这里temp是形如 wn125.000kg 的数据
if(!temp.equals("") && temp.length()==11)
{
return (change(temp)).toString();
}else{
return "";
}
}
//响应开始称重
public String startWeight(String num){
int n=Integer.parseInt(num.trim());
SerialBean SB = new SerialBean(n);
SB.Initialize();
return SerialBean.openSignal+""; //返回初始化信息
}
//响应停止称重
public void endWeight(){
try {
//关闭输入、输出流
SerialBean.in.close();
SerialBean.out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(SerialBean.serialPort!=null){
SerialBean.serialPort.close(); //关闭串口
}
SerialBean.serialPort=null;
SerialBean.portId=null;
SerialBean.result="";
}
public String change(String source){
Double result=0.0;
String s1=source.substring(2,9);
try{
result=Double.parseDouble(s1);
result=Arith.round(result,2);
}catch(Exception e){
e.printStackTrace();
return "";
}
return result.toString();
}
}
注:Arith.java是一个java 的高精度计算文件。
package com.chengzhong.tools;
import java.math.BigDecimal;
public class Arith{
//默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
//这个类不能实例化
private Arith(){
}
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doublevalue();
}
public static double sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doublevalue();
}
public static double mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doublevalue();
}
public static double div(double v1,double v2){
return div(v1,v2,DEF_DIV_SCALE);
}
public static double div(double v1,double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doublevalue();
}
public static double round(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doublevalue();
}
}
网页页面上:
dwr的使用就不说了
更多关于java相关内容感兴趣的读者可查看本站专题:《Java Socket编程技巧总结》、《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。



