Java implementation of serial communication sample

Source: Internet
Author: User


Using Java to implement serial communication (under Windows System), we need to use the port package Javacomm20-win32.zip provided by Sun. There are three files to use, such as the following configuration:

1.comm.jar placed to Java_home/jre/lib/ext;
2.win32com.dll placed to Java_home/bin;
3.javax.comm.properties two places to put them.

Jre/lib (that is, the JRE in the Java directory)

Java_home/jre/lib

Tell me about the environment I'm applying to. Electronic scale weighing, the computer through the serial port to the weighing control display to send a command "R", control the display to send a weight data to the serial port, the computer re-read the data displayed on the Web page. This makes up 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 reading result public static String result= "";p ublic static int OpenS ignal=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 was 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 other programs}else if (SerialBean.portId.getCurrentOwner (). Equals ("Serial_communication")) {Opensignal=1;return  OpenSignal;} return opensignal;} Use InputStream on to read from the serial port, and Outputstream//out to write to the serial port.try{in = SERIALPORT.G Etinputstream (); out = Serialport.getoutputstream ();}   catch (IOException e) {opensignal=3; Input output stream 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; The number of references is not return opensignal;}}  catch (Nosuchportexception e) {portid=null;  opensignal=5; No such serial port return opensignal;} When successfully open the serial port, create a new serial buffer,//then create a thread that consistently accepts in CominG Signals from//the serial port. Incoming signals is 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 is 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 Blocke.printstacktrace ();}} /**** This function sends a message through the serial port.** @param Msg the string to be sent.**/public static void writ  Eport (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 ();}}

This allows the reading result to be obtained by Serialbean.result.

As for putting the data on the Web, Ajax is used, and here's an AJAX framework Dwr, DWR class Put.java such as the following:

Package Com.chengzhong.dwr;import Java.io.ioexception;import Com.chengzhong.tools.arith;import Com.chengzhong.tools.serialbean;public class Put {//2011.9.17public String write () {//Send instruction R, The instrument transmits a net weight data serialbean.writeport ("R");//Read Data serialbean.readport ();   String Temp=serialbean.result.trim (); I am here temp is shaped like wn125.000kg data if (!temp.equals (") && temp.length () ==11) {return (change (temp)). ToString (); Else{return "";}} The response starts by weighing public string startweight (string num) {int n=integer.parseint (Num.trim ()); Serialbean SB = new Serialbean (n); TBI Initialize ();  return serialbean.opensignal+ ""; Returns initialization information}//response stop weighing public void endweight () {try {//off input, output stream SerialBean.in.close (); SerialBean.out.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}  if (serialbean.serialport!=null) {SerialBean.serialPort.close (); Close serial}serialbean.serialport=null; Serialbean.portid=null; Serialbean.result= "";} /** * Convert the weight of the form in wn125.000kg format to 125.000 (kg) (rounded, reserved two digits 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 computing file for Java.

Package Com.chengzhong.tools;import java.math.bigdecimal;/*** because the simple type of Java does not accurately calculate floating-point numbers, this tool class provides an accurate floating-point arithmetic, Contains subtraction and rounding.    */public class arith{//default division operation precision private static final int def_div_scale = 10;     This class cannot instantiate private Arith () {}/** * to provide precise addition operations. * @param v1 summand * @param v2 Addend * @return two parameters and */public static double Add (Double v1,double v2) {Bi        Gdecimal B1 = new BigDecimal (double.tostring (v1));        BigDecimal b2 = new BigDecimal (double.tostring (v2));    Return B1.add (B2). Doublevalue ();     }/** * provides precise subtraction operations. * @param v1 minuend * @param v2 * @return Two-parameter difference */public static double sub (double v1,double v2) {Bi        Gdecimal B1 = new BigDecimal (double.tostring (v1));        BigDecimal b2 = new BigDecimal (double.tostring (v2));    Return B1.subtract (B2). Doublevalue ();     }/** * provides accurate multiplication operations.  * @param v1 is multiplied by multiplier * @param v2 multiplier * @return Two parameters of the product */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 (relative) accurate division operations, when there are no more than an endless case, accurate to * after the decimal point 10 digits, after the number rounded. * @param v1 Dividend * @param v2 divisor * @return Two-digit quotient */public static double div (Double v1,double v2) {RE    Turn div (v1,v2,def_div_scale); }/** * provides (relative) accurate division operations.     When the exception occurs, the scale parameter refers to the fixed precision, after which the number is rounded.     * @param v1 Dividend * @param v2 divisor * @param scale indicates the need to be accurate to several points after the decimal point. * @return Two-parameter quotient */public static double div (double v1,double v2,int scale) {if (scale<0) {thro        W New IllegalArgumentException ("The scale must is 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 precise decimal roundingActing * @param v The number to be rounded * @param the scale after the decimal point retains several * @return rounded results */public static double round (double v,int  Scale) {if (scale<0) {throw new IllegalArgumentException ("The scale must is 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 (); }}


Page on 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);//Every half-second call get () on its own initiative, get gross data fill in the text box     } function get ()     {               ss.write (readit);    Call the  write method in the Dwr class Put.java        }     function Readit (Data) {            if (data!=null && data!= "")       {           document.getElementById ("MZBF"). Value=data;                }            } </script>




The use of DWR will not be said.

Java implementation of serial communication sample

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.