Java realizes serial port full-duplex communication

xiaoxiao2021-03-06  46

A embedded system typically requires full-duplex communication through serial ports, such as a pipeline control system needs to constantly accept query and control information sent from the main control system, and send the execution result or query results back to the master. system. This article describes a Java class library that implements a full-duplex communication through the serial port, which greatly simplifies the process of operating the serial port.

This class library mainly includes: SerialBean.java (interface with other applications), serialbuffer.java (used to save buffers that receive data received from the serial port), readserial.java (program read data from the serial port). In addition, this class library also provides a routine serialExample.java as a demonstration. These parts will be described in detail in the following content.

1. SerialBeanserialbean is an interface between this class library and other applications. The class library defines the construction method of the SerialBean and the initialization serial port, read data from the serial port, written to the serial port, and the function of turning off the serial port. Specific introduction is as follows:

Public serialbean (int portid) This function constructs a SerialBean pointing to a specific serial port, which is specified by the parameter portid. PortID = 1 represents COM1, PortID = 2 represents COM2, which is pushed. Public int initialize () This function initializes the specified serial port and returns the initialization result. If the initialization is successfully returned, -1 is returned. The result of the initialization is that the serial port is used exclusively by SerialBean, and its parameters are set to 9600, n, 8, and 1. If the serial port is successfully initialized, turn on a process to read the data incorporated from the serial port and save it in the buffer. Public String Readport (int LENGTH) This function reads a string of the specified length from the serial port (buffer). The parameter length specifies the length of the returned string. Public Void WritePort (String MSG) This function sends a string to the serial port. Parameter MSG is a string that needs to be sent. Public void closeport () This function stops the serial detection process and turn off the serial port.

The source code of SerialBean is as follows:

package serial; import java.io *;. import java.util *;. import javax.comm *;. / **** This bean provides some basic functions to implement full dulplex * information exchange through the srial port ** /. public class SerialBean {static String PortName; CommPortIdentifier portId; serialPort serialPort; static OutputStream out; static InputStream in; SerialBuffer SB; ReadSerial RT; / **** 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 commiNICivity. It Startss A * Thread Which Consistently Monitors . the serial port Any signal capturred * from the serial port is stored into a buffer area ** / public int Initialize () {int InitSuccess = 1;. int InitFail = -1; try {portId = CommPortIdentifier.getPortIdentifier (PortName); Try {serialport = (serialport) portid.open ("serial_communication", 2000);} catch (portinuseexception e) {return initfail;} // 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) {return InitFail;} // 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) {return InitFail;}} catch (NoSuchPortException e) { return InitFail;} // 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.SB =.

New serialbuffer (); rt = new readserial (SB, IN); rt.start (); // Return Success InformationReturn INITSUCCESS;} / **** This function returns a string with a certin length from the incomin * message. * * @Param Length the length of the string to be returned. ** / public string readport (int length) {string msg; msg = sb.getmsg (length); return msg;} / **** this function sends a message THROUGH the serial port. ** @Param msg the string to be sample. ** / public void writeport (string msg) {INT C; try {for (int i = 0; i

SerialBuffer is the serial buffer defined in this class library, which defines the functions required to write data into the buffer and read data from the buffer.

Public synchronized string getmsg (int future) This function reads a string of the specified length from the serial port (buffer). The parameter length specifies the length of the returned string. Public Synchronized Void Putchar (int C) This function is written in the serial port buffer, and the parameter c is a character that needs to be written. When writing data to the buffer or reading data from the buffer, the data is synchronized, so the getMSG and PUTCHAR functions are declared as synchronized and synchronization of data implemented in the specific implementation.

The source code of SerialBuffer is as follows:

package serial;. / **** This class implements the buffer area to store incoming data from the serial * port ** / public class SerialBuffer {private String Content = ""; private String CurrentMsg, TempContent; private boolean available = false; private int LengthNeeded = 1;.. / **** This function returns a string with a certain length from the incomin * messages ** @param length The length of the string to be returned ** / public synchronized String GetMsg (int length ) {LengthNeeded = Length; notifyAll (); if (LengthNeeded> Content.length ()) {available = false; while (available == false) {try {wait ();} catch (InterruptedException e) {}}} CurrentMsg = content.substring (0, LengthNeeded); TempContent = content.substring (LengthNeeded); Content = TempContent; LengthNeeded = 1; notifyAll (); return CurrentMsg;} / **** This function stores a character captured from the serial port To the * buffer area. ** @Param t the char value of the character to be stored. ** / public synchronized void Putchar (int C) {Character D = New Characte R (CHAR) C); Content = Content.concat (D. TnowTring ()); if (lengthneeded

Public Readserial (SerialBuffer SB, InputStream Port) This function constructs a REDSERIAL process, the parameter SB specifies the buffer that stores the incoming data, and the parameter port specifies the data stream received from the serial port. The main function of the Public Void Run () ReadSerial process, which is constantly read from the specified serial port and stores it into the buffer.

The source code of readserial is as follows:

package serial; import java.io *;. / **** This class reads message from the specific serial port and save * the message to the serial buffer ** / public class ReadSerial extends Thread {private SerialBuffer ComBuffer;. private InputStream ComPort ;. / **** Constructor ** @param SB The buffer to save the incoming messages * @param Port The InputStream from the specific serial port ** / public ReadSerial (SerialBuffer SB, InputStream Port) {ComBuffer = SB;. ComPort = Port;} public void run () {INT C; try {while (true) {c = comport.read (); combffer.putchar (c);}}}}}}} 4. SerialExampleSerialexample is A routine provided in this class library. The function it implemented is to open the serial port COM1, which is initialized, and the processing result is sent to the serial port after processing it from the serial port reading information.

Import serial. *; import java.io. *; / **** this is an esample of how to use the serialbean. it Opens com1 and reads * Six Messages with Different Length Form The Serial Port. ** / Class SerialExample { Public static void main (string [] args) {// to do: add your java code heselbean sb = new serialbean (1); string msg; sb.initialize (); for (int i = 5; i <= 10; i ) {msg = sb.readport (i); sb.writeport ("reply:" msg);} sb.closeport ();}}

5. Compilation and debugging

The Java Communication API (Javax.comm) is used in this class library. This is a Java extended class library and is not included in the standard Java SDK. If you have not already installed this extended class library, you should download this class library from Sun's Java Sites and install it on your system. In the downloaded package, you can find the serial port if you don't have the correct installation of this class library and its running environment.

Install the Java Communication API correctly and compile the above program, you can test this program as follows. If you have only one machine, you can connect COM1 and COM2 using a RS-232 cable, run SerialExample on COM1, running Windows on COM2. If you have two machines, you can connect the COM1 (or COM2) of the two machines using a RS-232 cable, run the routine at one end, and the other end runs the Hyper Terminal Program provided by Windows. If necessary, the serial port declared in SerialExample can be modified accordingly.

转载请注明原文地址:https://www.9cbs.com/read-56247.html

New Post(0)