Implement full-duplex serial communication using Java

Source: Internet
Author: User

This class library mainly includes: serialbean. java (interface with other applications), serialbuffer. java (used to save the buffer for data received from the serial port), readserial. java (the program that reads data from the serial port ). In addition, this class library provides a routine serialexample. Java as an example. The following sections describe these parts in detail.

Serialbean

Serialbean is the interface between this class library and other applications. This class library defines the serialbean constructor and the initialization serial port, reads data from the serial port, writes data to the serial port, and closes the serial function. The details are as follows:

Public serialbean (INT portid)
This function constructs a serialbean pointing to a specific serial port, which is specified by the portid parameter. Portid = 1 indicates COM1, portid = 2 indicates com2, and so on.
Public int initialize ()
This function initializes the specified serial port and returns the initialization result. If Initialization is successful, 1 is returned. Otherwise,-1 is returned. The initialization result is that the serial port is used exclusively by serialbean and its parameter is set to 9600, N, 8, 1. If the serial port is initialized successfully, open a process to read data imported 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 length parameter specifies the length of the returned string.
Public void writeport (string MSG)
This function sends a string to the serial port. The msg parameter is a string to be sent.
Public void closeport ()
This function stops the serial port detection process and closes 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 communication. 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 information            return InitSuccess;            }            /**             *             * This function returns a string with a certain length from the incomin             * 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 sends a message through the serial port.             *             * @param Msg The string to be sent.             *             */            public void WritePort(String Msg)            {                int c;                try                {                    for (int i = 0; i < Msg.length(); i++)                        out.write(Msg.charAt(i));                } catch (IOException e)  {}            }            /**             *             * This function closes the serial port in use.             *             */            public void ClosePort()            {                RT.stop();                serialPort.close();            }    }   


Back to Top

Serialbuffer

Serialbuffer is the Serial Buffer defined in this class library. It defines the functions required to write data into the buffer and read data from the buffer.

Public synchronized string getmsg (INT length)
This function reads a string of the specified length from the serial port (buffer. The length parameter specifies the length of the returned string.
Public synchronized void putchar (int c)
This function is intended to write a character in the Serial Buffer. Parameter C is the character to be written.
Data Synchronization must be ensured when writing data to or reading data from the buffer zone, therefore, the getmsg and putchar functions are declared as synchronized and take measures to achieve data synchronization in specific implementations.

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 Character((char) c);            Content = Content.concat(d.toString());            if (LengthNeeded < Content.length())            {                available = true;            }            notifyAll();        }    }   


Back to Top

Readserial

Readserial is a process that constantly reads data from the specified serial port and stores it in the buffer zone.

Public readserial (serialbuffer Sb, inputstreamport)
This function constructs a readserial process. The Sb parameter specifies the buffer zone for storing incoming data, and the port parameter specifies the data stream received from the serial port.
Public void run ()
The main function of the readserial process, which constantly reads data from the specified serial port and stores the data in the buffer zone.

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();                    ComBuffer.PutChar(c);                }            } catch (IOException e) {}        }    }


Back to Top

Serialexample

Serialexample is a routine provided by this class library. Its function is to enable the serial port COM1, initialize it, read the information from the serial port, process it, and send the processing result to the serial port.

   import serial.*;    import java.io.*;    /**     *     * This is an example 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 codes here            SerialBean 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();        }    }


Back to Top

Compilation and debugging

Java communication API (javax. Comm) is used in this class library ). This is a Java extension class library, not included in the standard Java SDK. If you have not installed this extension class library, you should download it from Sun's Java site and install it on your system. The downloaded package contains an installation Description. If you do not correctly install the class library and its running environment, you will not find the serial port when running this program.

After correctly installing the Java communication API and compiling the above program, you can test the program as follows. If you only have one machine, you can use a RS-232 cable to connect COM1 and com2, run serialexample on COM1, and run Windows-provided HyperTerminal program on com2. If you have two machines, you can use a RS-232 cable to connect the COM1 (or com2) of the two machines and run the routine at one end, the other end runs the Super Terminal Program provided by windows. If necessary, you can modify the serial port declared in serialexample.

This program is compiled and run successfully in Windows 2000 + Java SDK 1.3.

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.