当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现的串口通信功能示例

Java实现的串口通信功能示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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.*;
/**
*
* 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);
  } 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;
}
/**
*
* this function returns a string with a certain length from the incoming
* messages.
*
* @param length the length of the string to be returned.
*
*/
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();
}
}
/**
*
* this function sends a message through the serial port.
*
* @param msg the string to be sent.
*
*/
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;
}
}
/**
*
* this function closes the serial port in use.
*
*/
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="";
  }
  /**
      * 将形如 wn125.000kg 格式的重量转换为 125.000 (kg)(四舍五入,小数点后保留两位)
   */
   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;
/**
* 由于java的简单类型不能够精确的对浮点数进行运算,这个工具类提供精
* 确的浮点数运算,包括加减乘除和四舍五入。
*/
public class arith{
  //默认除法运算精度
  private static final int def_div_scale = 10;
  //这个类不能实例化
  private arith(){
  }
  /**
   * 提供精确的加法运算。
   * @param v1 被加数
   * @param v2 加数
   * @return 两个参数的和
   */
  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();
  }
  /**
   * 提供精确的减法运算。
   * @param v1 被减数
   * @param v2 减数
   * @return 两个参数的差
   */
  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();
  }
  /**
   * 提供精确的乘法运算。
   * @param v1 被乘数
   * @param v2 乘数
   * @return 两个参数的积
   */
  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();
  }
  /**
   * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
   * 小数点以后10位,以后的数字四舍五入。
   * @param v1 被除数
   * @param v2 除数
   * @return 两个参数的商
   */
  public static double div(double v1,double v2){
    return div(v1,v2,def_div_scale);
  }
  /**
   * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
   * 定精度,以后的数字四舍五入。
   * @param v1 被除数
   * @param v2 除数
   * @param scale 表示表示需要精确到小数点以后几位。
   * @return 两个参数的商
   */
  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();
  }
  /**
   * 提供精确的小数位四舍五入处理。
   * @param v 需要四舍五入的数字
   * @param scale 小数点后保留几位
   * @return 四舍五入后的结果
   */
  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();
  }
}

网页页面上:

<script type="text/javascript" src="/chengzhong/dwr/engine.js"></script>
<script type="text/javascript" src="/chengzhong/dwr/util.js"></script>
<script type='text/javascript' src='/chengzhong/dwr/interface/ss.js' ></script>
<script type='text/javascript' >
 var id;
   function begin(){
    id=window.setinterval('get()',500); //每隔半秒自动调用 get(),取得毛重数据填入文本框中
   }
 function get()
   {
    ss.write(readit);  //调用dwr类 put.java 中的write方法
   }
   function readit(data){
    if(data!=null && data!="")
    {
      document.getelementbyid("mzbf").value=data;
        }
   }
</script>

dwr的使用就不说了

更多关于java相关内容感兴趣的读者可查看本站专题:《java socket编程技巧总结》、《java文件与目录操作技巧汇总》、《java数据结构与算法教程》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网