最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java實現(xiàn)的串口通信功能示例

 更新時間:2018年01月17日 12:17:18   作者:逐兔郎  
這篇文章主要介紹了Java實現(xiàn)的串口通信功能,結合實例形式分析了java串口通信的具體操作步驟與相關注意事項,需要的朋友可以參考下

本文實例講述了Java實現(xiàn)的串口通信功能。分享給大家供大家參考,具體如下:

用Java實現(xiàn)串口通信(windows系統(tǒng)下),需要用到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

說一下我應用的環(huán)境。電子秤稱重時,計算機通過串口給稱重控制顯示器發(fā)送一次命令“R”,控制顯示器則發(fā)送一次重量數(shù)據(jù)給串口,計算機再讀取將數(shù)據(jù)顯示在網(wǎng)頁上。這樣就構成了一個實時稱重系統(tǒng)。

讀寫串口的代碼如下:

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;
//保存讀數(shù)結果
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;  //參數(shù)不正確
     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 就可得到讀數(shù)結果。

至于把數(shù)據(jù)放到網(wǎng)頁上,就要用到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(){
    //發(fā)送指令R,儀器發(fā)送一次凈重數(shù)據(jù)
    SerialBean.WritePort("R");
    //讀取數(shù)據(jù)
    SerialBean.ReadPort();
    String temp=SerialBean.result.trim();  //我這里temp是形如 wn125.000kg 的數(shù)據(jù)
    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)(四舍五入,小數(shù)點后保留兩位)
   */
   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的簡單類型不能夠精確的對浮點數(shù)進行運算,這個工具類提供精
* 確的浮點數(shù)運算,包括加減乘除和四舍五入。
*/
public class Arith{
  //默認除法運算精度
  private static final int DEF_DIV_SCALE = 10;
  //這個類不能實例化
  private Arith(){
  }
  /**
   * 提供精確的加法運算。
   * @param v1 被加數(shù)
   * @param v2 加數(shù)
   * @return 兩個參數(shù)的和
   */
  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 被減數(shù)
   * @param v2 減數(shù)
   * @return 兩個參數(shù)的差
   */
  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 被乘數(shù)
   * @param v2 乘數(shù)
   * @return 兩個參數(shù)的積
   */
  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();
  }
  /**
   * 提供(相對)精確的除法運算,當發(fā)生除不盡的情況時,精確到
   * 小數(shù)點以后10位,以后的數(shù)字四舍五入。
   * @param v1 被除數(shù)
   * @param v2 除數(shù)
   * @return 兩個參數(shù)的商
   */
  public static double div(double v1,double v2){
    return div(v1,v2,DEF_DIV_SCALE);
  }
  /**
   * 提供(相對)精確的除法運算。當發(fā)生除不盡的情況時,由scale參數(shù)指
   * 定精度,以后的數(shù)字四舍五入。
   * @param v1 被除數(shù)
   * @param v2 除數(shù)
   * @param scale 表示表示需要精確到小數(shù)點以后幾位。
   * @return 兩個參數(shù)的商
   */
  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();
  }
  /**
   * 提供精確的小數(shù)位四舍五入處理。
   * @param v 需要四舍五入的數(shù)字
   * @param scale 小數(shù)點后保留幾位
   * @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();
  }
}

網(wǎng)頁頁面上:

<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); //每隔半秒自動調(diào)用 get(),取得毛重數(shù)據(jù)填入文本框中
   }
 function get()
   {
    ss.write(readIt);  //調(diào)用dwr類 Put.java 中的write方法
   }
   function readIt(Data){
    if(Data!=null && Data!="")
    {
      document.getElementById("mzBF").value=Data;
        }
   }
</script>

dwr的使用就不說了

更多關于java相關內(nèi)容感興趣的讀者可查看本站專題:《Java Socket編程技巧總結》、《Java文件與目錄操作技巧匯總》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設計有所幫助。

相關文章

  • JAVA基本類型包裝類 BigDecimal BigInteger 的使用

    JAVA基本類型包裝類 BigDecimal BigInteger 的使用

    Java 中預定義了八種基本數(shù)據(jù)類型,包括:byte,int,long,double,float,boolean,char,short,接下來文章小編將向大家介紹其中幾個類型的內(nèi)容,需要的朋友可以參考下文章
    2021-09-09
  • java寫的偽微信紅包功能示例代碼

    java寫的偽微信紅包功能示例代碼

    這篇文章主要介紹了java寫的偽微信紅包功能示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-08-08
  • Java語法基礎之函數(shù)的使用說明

    Java語法基礎之函數(shù)的使用說明

    函數(shù)就是定義在類中的具有特定功能的一段小程序,函數(shù)也稱為方法
    2013-07-07
  • Mybatis中自定義TypeHandler處理枚舉詳解

    Mybatis中自定義TypeHandler處理枚舉詳解

    本文主要介紹了Mybatis中自定義TypeHandler處理枚舉的相關知識。具有很好的參考價值,下面跟著小編一起來看下吧
    2017-02-02
  • 詳解SpringBoot中的index首頁的訪問、自定義Favicon圖標

    詳解SpringBoot中的index首頁的訪問、自定義Favicon圖標

    這篇文章主要介紹了SpringBoot中的index首頁的訪問、自定義Favicon圖標,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-08-08
  • Java實現(xiàn)兩個日期相減等于天數(shù)

    Java實現(xiàn)兩個日期相減等于天數(shù)

    這篇文章主要介紹了Java兩個日期相減等于天數(shù)的實現(xiàn)方式,本文通過兩種方式結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-09-09
  • 淺析Java中如何實現(xiàn)線程之間通信

    淺析Java中如何實現(xiàn)線程之間通信

    本篇文章主要介紹了淺析Java中如何實現(xiàn)線程之間通信。針對 Java 的線程間通信進行了大致的講解,有興趣的可以了解一下
    2017-04-04
  • mybatisPlus批量插入優(yōu)化加快性能

    mybatisPlus批量插入優(yōu)化加快性能

    這篇文章主要介紹了mybatisPlus批量插入優(yōu)化加快性能,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-12-12
  • 詳解Spring配置及事務的使用

    詳解Spring配置及事務的使用

    這篇文章主要介紹了詳解Spring配置及事務的使用,文中附含詳細的示例代碼說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-09-09
  • SpringBoot+Vue添加騰訊云人臉識別的項目實踐

    SpringBoot+Vue添加騰訊云人臉識別的項目實踐

    人臉識別是一種基于人臉特征進行身份認證和識別的技術,本文主要介紹了SpringBoot+Vue添加騰訊云人臉識別的項目實踐,具有一定的參考價值,感興趣的可以了解一下
    2023-08-08

最新評論

高清| 冷水江市| 和硕县| 宁南县| 康马县| 抚松县| 丹东市| 汤原县| 江门市| 汝州市| 调兵山市| 景德镇市| 隆尧县| 凌云县| 闵行区| 九寨沟县| 桂东县| 扶余县| 河东区| 常宁市| 卢龙县| 沈丘县| 盐池县| 青神县| 肥乡县| 苏州市| 达州市| 东丽区| 佛坪县| 伊宁县| 新平| 潞西市| 城固县| 于田县| 壶关县| 平遥县| 正宁县| 青岛市| 漯河市| 成武县| 黑水县|