This article describes the serial communication function implemented by Java. Share it for your reference, as follows:
To implement serial communication using Java (under Windows system), you need to use the serial port package javacomm20-win32.zip provided by Sun. Three files are used, and the configuration is as follows:
1.comm.jar is placed in JAVA_HOME/jre/lib/ext;
2.Place win32com.dll to JAVA_HOME/bin;
3.javax.comm.properties Both places must be placed
jre/lib (that is, jre under the JAVA folder)
JAVA_HOME/jre/lib
Let me talk about the environment I applied. When weighing an electronic scale, the computer sends the command "R" to the weighing control monitor through the serial port, and the control monitor sends the weight data to the serial port once, and the computer then reads the data to display it on the web page. This forms a real-time weighing system.
The code for reading and writing the 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 the reading result 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; //This serial port is occupied by other programs}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; //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; //The parameter is incorrect 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 informationreturn 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();}} In this way, you can get the reading result through SerialBean.result .
As for putting data on a web page, Ajax needs to be used. Here is an Ajax framework dwr, dwr class Put.java is used 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 instruction R, the instrument sends net weight data SerialBean.WritePort("R"); //Read data SerialBean.ReadPort(); String temp=SerialBean.result.trim(); //I am temp here to be wn125.000kg of data if(!temp.equals("") && temp.length()==11) { return (change(temp)).toString(); }else{ return ""; } } //Response start weighing public String startWeight(String num){ int n=Integer.parseInt(num.trim()); SerialBean SB = new SerialBean(n); SB.Initialize(); return SerialBean.openSignal+""; //Return initialization information}//Response stop weighing public void endWeight(){ try { //Close 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 the serial port} SerialBean.serialPort=null; SerialBean.portId=null; SerialBean.result=""; } /** * Convert weight in the format of wn125.000kg to 125.000 (kg) (rounded, two digits retained after 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 for java.
package com.chengzhong.tools;import java.math.BigDecimal;/*** Since Java's simple types cannot accurately perform operations on floating-point numbers, this tool class provides accurate floating-point operations, including addition, subtraction, multiplication and division, and rounding. */public class Arith{ //Default division operation accuracy private static final int DEF_DIV_SCALE = 10; //This class cannot be instantiated private Arith(){ } /** * Provides accurate addition operations. * @param v1 added* @param v2 add* @return The sum of the 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 is subtracted* @param v2 is subtracted* @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 operations. * @param v1 multiplier* @param v2 multiplier* @return 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 there is no division, it is accurate to * 10 digits after the decimal point, and the subsequent numbers are rounded. * @param v1 Divider* @param v2 Divider* @return Quotation of two parameters*/ public static double div(double v1,double v2){ return div(v1,v2,DEF_DIV_SCALE); } /** * Provides (relatively) accurate division operation. When there is no end to complete the separation, the scale parameter refers to the accuracy of *, and the subsequent numbers are rounded. * @param v1 Divider* @param v2 Divider* @param scale means that it needs to be accurate to several digits after the decimal point. * @return 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(); } /** * Provides accurate decimal rounding. * @param v Counts that need to be rounded* @param scale How many digits are retained after the decimal point* @return The result after rounding*/ 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 call get() every half a second, get the gross weight data and fill it in the text box} function get() { ss.write(readIt); //Calling the write method in the dwr class Put.java} function readIt(Data){ if(Data!=null && Data!="") { document.getElementById("mzBF").value=Data; } }</script>I won't talk about the use of dwr
For more information about Java related content, please check out the topics of this site: "Summary of Java Socket Programming Skills", "Summary of Java File and Directory Operation Skills", "Tutorial on Java Data Structure and Algorithm", "Summary of Java Operation DOM Node Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.