Implementation and debugging of communication between Java program and serial port

Posted by meritre on Sun, 12 May 2019 00:33:59 +0200

Below is a brief introduction of Xiaobian's latest project, involving the realization and debugging of serial communication.

Principle of Serial Communication

  1. Serial communication refers to sending and receiving bytes by bit. Although it is slower than byte parallel communication, the serial port can receive data with another line while sending data with one line.
  2. Serial port is a very common device communication protocol on computers (don't confuse it with Universal Serial Bus or USB)
  3. Typically, serial ports are used for ASCII code character transmission. Communication is accomplished by three wires: (1) ground, (2) sending, (3) receiving. Because serial communication is asynchronous, ports can send data on one line and receive data on another. Other lines are used to shake hands, but not necessarily. The most important parameters of serial communication are bit rate, data bit, stop bit and parity check. For two communication ports, these parameters must match
  4. RS-232 (ANSI/EIA-232) is the serial connection standard for IBM-PC and its compatible computers. RS-422 (EIA RS-422-AStandard) is the serial connection standard for Apple's Macintosh computers. RS-485 (EIA-485 standard) is an improvement of RS-422.

Preparations for serial communication and debugging on a computer

Since there are basically no pairs of serial ports on notebooks or desktops for debugging, we need to download virtual serial port software to achieve serial debugging.

  1. Download Virtual Serial Port Software http://pan.baidu.com/s/1hqhGDbI It's better to use it here. After downloading and installing, don't rush to run. Copy the vspdctl.dll file in the compressed package to the installation directory as follows: My directory is -> D: SoftWareInstall Virtual Serial Port Driver 7.2 to replace the original file and activate successfully.
  2. Open software to add virtual serial ports, usually in pairs (add COM3, COM4), as shown in the figure:
  3. After the addition is completed, we look in the Device Manager and find that there are two more virtual serial ports as shown in the figure:So far, the work of creating virtual serial port has been completed.
  4. Download Serial Port Debugging Software http://pan.baidu.com/s/1c0AVaXq Here is the older debugging software, but it is still better to use. Just unzip it and click on it to open it.
  5. Two debugging windows can be opened directly to represent COM3 and COM4 serial ports, respectively. The parameters of the two serial ports must be set the same in order to send and receive data normally. (If debugging can normally send and receive data, you can turn off a debugger and replace it with a java program.) Figure 1:

java program code writing

This part will be our focus. To communicate with the serial port, we first need to add RXTXcomm.jar package to the project (placed in the lib directory of the project and added to the build Path) (win64-bit download address: http://pan.baidu.com/s/1o6zLmTc In addition, the decompressed rxtxParallel.dll and rxtxSerial.dll files need to be placed in the% JAVA_HOME%/jre/bin directory so that the package can be loaded and invoked normally.

Program code parsing:

package comm;

import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import gnu.io.*;

public class ContinueRead extends Thread implements SerialPortEventListener { // SerialPortEventListener
    // Listener, my understanding is to create a thread to listen for serial data independently
    static CommPortIdentifier portId; // Serial Communication Management Class
    static Enumeration<?> portList; // Enumeration of ports on valid connections
    InputStream inputStream; // Input stream from serial port
    static OutputStream outputStream;// Stream output to serial port
    static SerialPort serialPort; // Reference to Serial Port
    // Blocked queues are used to store read data
    private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();

    @Override
    /**
     * SerialPort EventListene Method to continuously listen for data streams on ports
     */
    public void serialEvent(SerialPortEvent event) {//

        switch (event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:// Read data when available
            byte[] readBuffer = new byte[20];
            try {
                int numBytes = -1;
                while (inputStream.available() > 0) {
                    numBytes = inputStream.read(readBuffer);

                    if (numBytes > 0) {
                        msgQueue.add(new Date() + "The real data received are:-----"
                                + new String(readBuffer));
                        readBuffer = new byte[20];// Reconstruct the buffer object, otherwise it may affect the next data received
                    } else {
                        msgQueue.add("forehead------No data read");
                    }
                }
            } catch (IOException e) {
            }
            break;
        }
    }

    /**
     * 
     * Open COM4 serial port through program, set listener and related parameters
     * 
     * @return Return 1 indicates that the port was opened successfully, and return 0 indicates that the port failed to open.
     */
    public int startComPort() {
        // Get the list of serial ports on the current connection through the serial communication management class
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {

            // Get the corresponding serial object
            portId = (CommPortIdentifier) portList.nextElement();

            System.out.println("Equipment type:--->" + portId.getPortType());
            System.out.println("Device Name:---->" + portId.getName());
            // Determine whether the port type is a serial port
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // Judge if COM4 Serial Port exists, open the Serial Port
                if (portId.getName().equals("COM4")) {
                    try {
                        // Open the serial port with the name COM_4 (any name), with a delay of 2 milliseconds
                        serialPort = (SerialPort) portId.open("COM_4", 2000);

                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // Setting the input and output stream of the current serial port
                    try {
                        inputStream = serialPort.getInputStream();
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // Add a listener to the current serial port
                    try {
                        serialPort.addEventListener(this);
                    } catch (TooManyListenersException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // Setting up a listener takes effect, i.e. notifying when data is available
                    serialPort.notifyOnDataAvailable(true);

                    // Setting Some Read and Write Parameters of Serial Port
                    try {
                        // Bit Rate, Data Bit, Stop Bit, Parity Check Bit
                        serialPort.setSerialPortParams(9600,
                                SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {
                        e.printStackTrace();
                        return 0;
                    }

                    return 1;
                }
            }
        }
        return 0;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            System.out.println("--------------Task Processing Thread Runs--------------");
            while (true) {
                // If there is data in the blocked queue, output it
                if (msgQueue.size() > 0) {
                    System.out.println(msgQueue.take());
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ContinueRead cRead = new ContinueRead();
        int i = cRead.startComPort();
        if (i == 1) {
            // Start threads to process incoming data
            cRead.start();
            try {
                String st = "Ha-ha----Hello";
                System.out.println("Number of bytes issued:" + st.getBytes("gbk").length);
                outputStream.write(st.getBytes("gbk"), 0,
                        st.getBytes("gbk").length);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            return;
        }
    }
}

Debugging of communication between java program and serial port

Program debugging screenshot:

summary

  1. Serial communication is used in many places, especially in embedded development, short message module development and customized software for various hardware products. The most commonly used communication protocol is RS-232 communication protocol. To become a real master of serial communication development, it is necessary to have a comprehensive understanding of the serial communication protocol (I am still a novice...). Hope to have a good finger.
  2. Another key point of serial communication is how to judge the type of data and extract the valid data after receiving the data. All of these need to be coded according to the corresponding protocol.

Topics: Java ascii Windows