Principle of serial communication

  1. Serial port communication means that the serial port sends and receives bytes in bits. Although slower than parallel communication by byte, a serial port can use one line to send data while using another line to receive data.
  2. Serial port is a very common device communication protocol on computers (not to be confused with Universal SerialBus or USB)
  3. Typically, serial ports are used for transmission of ASCII characters. Communication is accomplished by three wires :(1) ground, (2) sending, and (3) receiving. Because serial communication is asynchronous, a port can send data on one wire and receive data on another. Other lines are used for handshaking, but are not required. The most important parameters of serial communication are bit rate, data bit, stop bit and parity check. For two ports that communicate, these parameters must match
  4. Rs-232 (ANSI/EIA-232 standard) is the serial connection standard for IBM-PCS and their compatibles, and RS-422 (EIA RS-422-ASTandard) is the serial connection standard for Apple Macintosh computers. Rs-485 (EIA-485 standard) is an improvement on rS-422.

What do we need to do on a computer to implement Java serial communication?

Since there is basically no pair of serial ports for debugging on laptops or desktops, we need to download virtual serial port software to achieve serial port debugging. Of course, if you are soft and hard, hardware equipment in the side of the words, then you ignore this step of operation]

  1. Download virtual serial software ** : download the installation after the first do not rush to run, the compressed package in the vspdctl. DLL file copy to the installation directory to replace the original file can be successfully activated.

  2. Open the software to add the virtual serial port, which is generally added in pairs (add COM3 and COM4), as shown in the figure (add string 2 ports according to your own needs) :

  3. After the addition, check the device manager and find two more virtual serial ports as shown in the figure below:

    This indicates that the virtual interface has been created successfully, and you can proceed to the next step.

  4. Download serial debugging software: this software is relatively easy to use. Just unzip it and click open.

  5. You can directly open two debug Windows, respectively used to represent COM3 and COM4 serial ports. The parameters of the two serial ports must be set the same. (If the debugger can send and receive data normally, you can turn off a debugger and use a Java program instead.)

Java code writing and debugging

This section will be our focus. To communicate with the serial port, first add the rxtxcomm.jar package to the project (put it in the lib directory of the project and add it to the build Path).

DLL and rxtxSerial. DLL must be stored in the %JAVA_HOME%/jre/bin directory so that the package can be loaded and invoked normally. Jar –> <JAVA_HOME>\jre\lib\ext; Copy rxtxSerial.dll –><JAVA_HOME>\jre\bin; Copy rxtxParallel. DLL –><JAVA_HOME>\jre\bin) 】

* * note: ** Install to %JAVA_HOME%/jre/bin — need to install in tomacat JDK, remember to use tomcat to run the JDK, including the development environment, The JDK is not the same as the JDK that Tomcat runs. The servers JDK is not the same as the JDK that Tomcat runs.

If it is not under the tomacat JDK complains: Java. Lang. UnsatisfiedLinkError: no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDriver

The solution is to import the above files into the correct path.

Java connection transfer data code block:

package Chuankou; import java.io.*; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import gnu.io.*; public class ContinueckRead extends Thread implements SerialPortEventListener { // SerialPortEventListener // Static CommPortIdentifier portId; static CommPortIdentifier portId; Static Enumeration<? > portList; // Enumeration of ports on valid connections InputStream InputStream; // Input stream from serial port static OutputStream OutputStream; // stream output to SerialPort static SerialPort SerialPort; Private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>(); 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;
        caseSerialportevent. 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 actual received data is: -----"
                                + new String(readBuffer));
                        readBuffer = new byte[20]; // Reframe the buffer object, otherwise it may affect the data to be received later}else {
                        msgQueue.add("Err ------ did not read the data");
                    }
                }
            } catch (IOException e) {
            }
            break; }} /** ** open COM4 serial port through the program, set the listener and related parameters ** @returnIf 1 is returned, the port is opened successfully, and if 0 is returned, the port is opened failed */ public intstartComPort() {/ / via a serial port communication management class for a serial port on the current connection list portList = CommPortIdentifier. GetPortIdentifiers ();while(portlist.hasmoreElements ()) {// Obtain the corresponding serial port object portId = (CommPortIdentifier) portList.nextelement (); System.out.println("Device Type: --> + portId.getPortType());
            System.out.println("Device name: ---->"+ portId.getName()); // Check whether the port type is serial portif(portid.getPortType () == CommPortIdentifier.PORT_SERIAL) {// Check whether the COM4 serial port existsif (portId.getName().equals("COM4:USB-SERIAL"SerialPort = (serialPort) portid.open (serialPort = (serialPort) portid.open ("COM_4", 2000);
 
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        return0; } / / set the current input and output flow of the serial port try {inputStream. = serialPort getInputStream (); outputStream = serialPort.getOutputStream(); } catch (IOException e) { e.printStackTrace();return0; } / / add a listener to the current serial try {serialPort. AddEventListener (this); } catch (TooManyListenersException e) { e.printStackTrace();return0; } / / set the listeners to take effect, i.e., when have data to inform the serialPort. NotifyOnDataAvailable (true); / try/set some of the serial port to read and write parameters {/ / bit rate, data bits, stop bits, parity bit serialPort. SetSerialPortParams (9600, serialPort. DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { e.printStackTrace();return 0;
                    }
 
                    return1; }}}return 0;
    }
 
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            System.out.println("-------------- task processing thread running --------------");
            while (true) {// If there is data in the blocked queue, output itif (msgQueue.size() > 0) {
                    System.out.println(msgQueue.take());
                }
            }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        ContinueckRead cRead = new ContinueckRead();
        int i = cRead.startComPort();
        if(I == 1) {// Start the thread to process the received data cread.start (); try { String st ="Ha ha ---- Hello";
                System.out.println("Sent bytes:" + 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; }}}Copy the code

Result of communication between Java program and serial port:

Program and XCOM joint debugging:

Finally, this content about Java and serial communication is over, I hope to help you.