Java-implemented serial communication function example, java Serial Communication Example

Source: Internet
Author: User

Java-implemented serial communication function example, java Serial Communication Example

This example describes the serial communication implemented by Java. We will share this with you for your reference. The details are as follows:

Realize serial port communication with Java (windows System), need to use the serial port package javacomm20-win32.zip provided by sun. Three files are used. The configuration is as follows:

1. Place comm. jar in JAVA_HOME/jre/lib/ext;
2. Place win32com. dll in JAVA_HOME/bin;
3. Both javax. comm. properties must be placed.
Jre/lib (that is, the jre in the JAVA folder)
JAVA_HOME/jre/lib

Let's talk about my application environment. When weighing an electronic scale, the computer sends the command "R" to the weighing control display through the serial port, and the control display sends the weight data to the serial port. The computer then reads the data and displays it on the webpage. This constitutes a real-time weighing system.

The code for reading and writing serial ports is as follows:

Package com. chengzhong. tools; import java. io. *; import javax. comm. commp ortidentifier; 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 commp ortidentifier portId; public static SerialPort serialPort; public static OutputStream out; public static Indium UtStream 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 s Erial port is stored into a buffer area. **/public int Initialize () {openSignal = 1; try {portId = comatrix ortidentifier. 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;} // Use InputStream in to read from the serial port, and OutputStream // out to write to the serial port. try {in = serialPort. getInputStream (); out = serialPort. getOutputS Tream ();} 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; // return openSignal with incorrect parameters;} catch (NoSuchPortException e) {portId = null; openS Ignal = 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 informationreturn openSignal;}/***** This function returns a string with a certain length from the incoming * messages. ** @ param Lengt H 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 waySerialBean.resultYou can get the reading result.

As for putting data on a webpage, Ajax is required. Here we use an Ajax framework dwr, And the dwr class Put. 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 command R, the instrument sends the net data SerialBean once. writePort ("R"); // read data SerialBean. readPort (); String temp = SerialBean. result. trim (); // here temp is the data like wn125. 000kg if (! Temp. equals ("") & temp. length () = 11) {return (change (temp )). toString () ;}else {return "" ;}// the response starts to weigh 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 to stop weighing public void endWeight () {try {// close the input and 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 the serial port} SerialBean. serialPort = null; SerialBean. portId = null; SerialBean. result = "";}/*** converts the weight in the wn125. 000kg format to 125.000 (kg) (rounded to 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 java high-precision computing file.

Package com. chengzhong. tools; import java. math. bigDecimal;/*** Because Java's simple type cannot accurately perform floating-point operations, this tool class provides precise * real floating-point operations, including addition, subtraction, multiplication, division, and rounding. */Public class Arith {// default Division calculation precision: private static final int DEF_DIV_SCALE = 10; // This class cannot be instantiated private Arith () {}/*** provides precise addition operations. * @ Param v1 add count * @ param v2 add count * @ return and */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 precise subtraction. * @ Param v1 subtrahend * @ param v2 subtrahend * @ return Difference Between 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 exact multiplication. * @ 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) Precise Division operations. In case of Division, the Division is accurate to * 10 digits after the decimal point, and the subsequent digits are rounded down. * @ Param v1 divisor * @ param v2 divisor * @ return two parameter vendors */public static double div (double v1, double v2) {return div (v1, v2, DEF_DIV_SCALE);}/*** provides (relatively) accurate Division operations. In case of division, the scale parameter determines * the precision, and the number is rounded down. * @ Param v1 divisor * @ param v2 divisor * @ param scale indicates the number of digits after the decimal point. * @ Return operator 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 precise rounded decimal places. * @ Param v the number to be rounded off * @ param scale the number of digits to be 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 webpage:

<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); // get () is automatically called every half second to obtain Gross weight data. Fill in the text box} function get () {ss. write (readIt); // call the dwr class Put. java The write method} function readIt (Data) {if (Data! = Null & Data! = "") {Document. getElementById ("mzBF"). value = Data ;}</script>

Dwr is not used.

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.