Using Java to implement serial port full-duplex communication

zhaozj2021-02-08  306

Sender: qyjohn (Sweet Potato - Successful ring BBS ...) : 40 2001) Using Java to implement serial port full-duplex communication (submission) Qingye Jiang (John) SMTH ID: Qyjohne-mail: Qjiang@tsinghua.edu A embedded system usually needs to communicate full-duplex communication with its main control system, For example, 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 main control 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. The 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.

SerialBean source code 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 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 () {int InitSuccess = 1;. int InitFail = -1; try {portId = CommPortIdentifier .Getportidentifier (portname); try {serialport = (serialport) portid.open ("serial_communication", 2000);} catch (portinuseexcection e) {return initfail;} // use inputStream I n 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) {returnin 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 ceerting returns a string with a certin length from the incoming * messages. ** @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 sereds a message through the serial port. ** @Param msg the string to be slow. ** / public void writeport (string msg) {INT C; try {for (INT i = 0; i

SerialBuffer source code 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 incoming * 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) {Charact ER D = New Character ((char) C); Content = Content.concat (D. TnowTring ()); if (Lengthneeded

ReadSerial source code 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 () {c = comport.read (); combffer.putchar (c);}} catch (ooException e) {} }} 4. SerialExampleSerialexample is a routine provided by 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);}}}}}}}}}} 5. Compiling and debug this class library Used Java Communication API (Javax. COMM). 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-876.html

New Post(0)