Using Java to implement serial communication (under Windows System), we need to use the serial javacomm20-win32.zip provided by Sun. There are three files to use, configured as follows:
1.comm.jar placed to Java_home/jre/lib/ext;
2.win32com.dll placed to Java_home/bin;
3.javax.comm.properties two places.
Jre/lib (that is, JRE under the Java folder)
Java_home/jre/lib
Tell me about the environment I applied. Electronic scale weighing, the computer through the serial port to the weighing control monitor sent a command "R", control display to send a weight data to the serial port, the computer to read the data displayed on the Web page. In this way, a real-time weighing system is formed.
Read-write serial code 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 Ser
Ialport 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 are stored into a-buffer area.
* */public int Initialize () {opensignal=1; try {Portid = Commportidentifier.getportidentifier (portnAME);
try {serialPort = (serialPort) portid.open ("Serial_communication", 2000); The 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 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;
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 parameter is incorrect return opensignal;
catch (Nosuchportexception e){portid=null; opensignal=5;
No this serial port return opensignal; }//When successfully open the serial port, create a new serial buffer,//Then create a thread that consistently acce PTS 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));
The catch (IOException e) {return;
}/** * * This function closes the serial port.
* */public void Closeport () {serialport.close ();}}
In this way, the reading result can be obtained by Serialbean.result.
As for putting the data on the Web page, it's going to use Ajax, and here's an AJAX framework Dwr, DWR class Put.java 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 a net weight data serialbean.writeport ("R");
Read Data serialbean.readport (); String Temp=serialbean.result.trim ();
I'm here temp is shaped like wn125.000kg 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); TBI
Initialize (); return serialbean.opensignal+ "";
Returns initialization information}//Response stop weighing public void endweight () {try {//close input, Output stream SerialBean.in.close ();
SerialBean.out.close ();
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } if (Serialbean.serialport!=null) {SerialBean.serialPort.close (); Close serial Port} SeriAlbean.serialport=null;
Serialbean.portid=null;
Serialbean.result= ""; /** * Converts the weight of the form, such as wn125.000kg format, to 125.000 (kg) (rounded, reserved two digits after the decimal point) */public String change (String source) {D
Ouble 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 Java High Precision computing file.
Package com.chengzhong.tools;
Import Java.math.BigDecimal;
/** * Because Java's simple type does not accurately operate on floating-point numbers, this tool class provides precision floating-point operations, including subtraction and rounding.
*/public class arith{//default division precision private static final int def_div_scale = 10;
This class cannot instantiate private Arith () {}/** * provides exact addition operations.
* @param v1 summand * @param v2 addends * @return two parameters and/or 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 an accurate subtraction operation.
* @param v1 Bing * @param v2 * @return Two parameters of the difference * * 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 an accurate multiplication operation. * @param v1 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, which, when occurring in addition to the circumstances, are accurate to the 10 digits after the decimal point, after which the numbers are rounded.
* @param v1 Dividend * @param v2 divisor * @return Two parameters of the quotient/public static double div (Double v1,double v2) {
Return Div (V1,v2,def_div_scale); /** * provides (relative) precise division operations.
When it occurs, the scale parameter refers to the fixed precision, and the subsequent digits are rounded up.
* @param v1 Dividend * @param v2 divisor * @param scale indicated that the need to be accurate to several decimal places.
* @return Two-parameter quotient/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 processing. * @param v to be rounded number * @param scale decimal point after a few * @return rounded results * * 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 page 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 automatically calls get (), gets the gross weight data fills in the text box
}
function getting ()
{
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