Example of serial communication function implemented by Java

  • 2020-12-26 05:46:29
  • OfStack

This paper illustrates the serial port communication function of Java. To share for your reference, the details are as follows:

To realize serial communication with Java (under windows system), the serial port package es7EN20-win32.ES9en provided by sun is needed. Three files are needed, and the configuration is as follows:

1. comm. Put the jar JAVA_HOME/jre/lib/ext;
2.win32com.dll to JAVA_HOME/bin;
3.javax.comm.properties
jre/lib(jre under JAVA)
JAVA_HOME/jre/lib

Say 1 for the environment I'm using. When weighing on the electronic scale, the computer sends the command "R" once to the weighing control display through the serial port, and the control display sends the weight data to the serial port once, and then the computer reads and displays the data on the web page. Thus, a real-time weighing system is formed.

The code of read and write serial port is as follows:


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;
// Save reading results 
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; // The serial port is occupied by another program 
    }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;  // I/O flow error 
     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;  // Incorrect parameter 
     return openSignal;
  }
  } catch (NoSuchPortException e)
  {
     portId=null;
     openSignal=5; // There is no serial port 
     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();
}
}

So through SerialBean.result You get a reading.

As for putting the data on the web page, Ajax is used. Here, an Ajax framework dwr is used. The dwr class ES52en.java is as follows:


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(){
    // Send instructions R Instrument transmission 1 Secondary net weight data 
    SerialBean.WritePort("R");
    // Read the data 
    SerialBean.ReadPort();
    String temp=SerialBean.result.trim();  // I am here temp Is like  wn125.000kg  The data of 
    if(!temp.equals("") && temp.length()==11)
    {
       return (change(temp)).toString();
    }else{
      return "";
    }
  }
  // Response starts weighing 
  public String startWeight(String num){
     int n=Integer.parseInt(num.trim());
     SerialBean SB = new SerialBean(n);
     SB.Initialize();
     return SerialBean.openSignal+""; // Returns initialization information 
  }
// Response stop weighing 
  public void endWeight(){
    try {
      // Close the input and output streams 
      SerialBean.in.close();
      SerialBean.out.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if(SerialBean.serialPort!=null){
      SerialBean.serialPort.close(); // Close a serial port 
    }
    SerialBean.serialPort=null;
    SerialBean.portId=null;
    SerialBean.result="";
  }
  /**
      *  Will be like  wn125.000kg  Format the weight to convert to  125.000 (kg)(4 Give up 5 I'm going to put two digits behind the decimal point )
   */
   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();
   }
}

Note: Arith.java is a high precision calculation file of java.


package com.chengzhong.tools;
import java.math.BigDecimal;
/**
*  Due to the Java This utility class provides refinement of the simple types that do not perform precision operations on floating point numbers 
*  True floating-point arithmetic, including addition, subtraction, multiplication, and division 4 Give up 5 Into the. 
*/
public class Arith{
  // Default division precision 
  private static final int DEF_DIV_SCALE = 10;
  // This class cannot be instantiated 
  private Arith(){
  }
  /**
   *  Provides accurate addition operations. 
   * @param v1  augend 
   * @param v2  addend 
   * @return  The sum of two parameters 
   */
  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();
  }
  /**
   *  Provides accurate subtraction operations. 
   * @param v1  minuend 
   * @param v2  reduction 
   * @return  The difference between the two parameters 
   */
  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();
  }
  /**
   *  Provides accurate multiplication. 
   * @param v1  multiplicand 
   * @param v2  The multiplier 
   * @return  The product of two parameters 
   */
  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();
  }
  /**
   *  Provides (relatively) accurate division operation, when the case of endless division, accurate to 
   *  After the decimal point 10 Bits, later numbers 4 Give up 5 Into the. 
   * @param v1  dividend 
   * @param v2  divisor 
   * @return  The quotient of two parameters 
   */
  public static double div(double v1,double v2){
    return div(v1,v2,DEF_DIV_SCALE);
  }
  /**
   *  Provides (relatively) accurate division operations. When an inexhaustibility occurs, by scale Parameter refers to 
   *  Fixed precision, subsequent numbers 4 Give up 5 Into the. 
   * @param v1  dividend 
   * @param v2  divisor 
   * @param scale  To be accurate to a few places below the decimal point. 
   * @return  The quotient of two parameters 
   */
  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();
  }
  /**
   *  Provide the exact decimal place 4 Give up 5 In the process. 
   * @param v  Need to be 4 Give up 5 Into the digital 
   * @param scale  Keep a few places behind the decimal point 
   * @return 4 Give up 5 Results after entry 
   */
  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();
  }
}

On the web page:


<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); // Automatically called every half second  get(), Get the gross weight data and fill in the text box 
   }
 function get()
   {
    ss.write(readIt);  // call dwr class  Put.java  In the write methods 
   }
   function readIt(Data){
    if(Data!=null && Data!="")
    {
      document.getElementById("mzBF").value=Data;
        }
   }
</script>

Let's not talk about dwr

For more information about java, please refer to Java Socket Programming Skills summary, Java Files and directories Operation Skills Summary, Java Data Structure and Algorithm Tutorial, Java Operation DOM Node Skills Summary and Java Cache Operation Skills Summary.

I hope this article is helpful for java programming.


Related articles: