search
HomeJavajavaTutorialImplementation and debugging of communication between Java program and serial port

The following is an introduction to the editor’s latest project, which involves the implementation and debugging of the serial port communication part.

Serial communication principle

Serial communication refers to the serial port sending and receiving bytes bit by bit. Although slower than byte-by-byte parallel communication, a serial port can send data on one wire while receiving data on another wire.

Serial port is a very common device communication protocol on computers (not to be confused with Universal SerialBus or USB)

Typically, serial port is used for the transmission of ASCII code characters. Communication is done using 3 wires: (1) ground, (2) transmit, (3) receive. Because serial communication is asynchronous, a port can send data on one line while receiving data on another line. The other lines are used for handshaking, but are not required. The most important parameters for serial communication are bit rate, data bits, stop bits and parity. For two ports to communicate, these parameters must match

RS-232 (ANSI/EIA-232 standard) is a serial connection standard on IBM-PC and its compatible machines, RS-422 (EIA RS-422-AStandard) It is the serial port connection standard for Apple's Macintosh computers. RS-485 (EIA-485 standard) is an improvement of RS-422.

Complete the preparation work required for serial port communication and debugging on a computer

Since there are basically no paired serial ports on laptops or desktops for us to debug, we need to download virtual serial port software to achieve serial port debugging.

Download the virtual serial port software http://pan.baidu.com/s/1hqhGDbI (the one provided here is relatively easy to use). After the download and installation is completed, don’t rush to run it. Copy the vspdctl.dll file in the compressed package to the installation directory, such as: My directory is –>D:SoftWareInstallVirtual Serial Port Driver 7.2. Replace the original file and activate successfully.

Open the software to add virtual serial ports, which are usually added in pairs (add COM3, COM4) as shown in the picture:

Implementation and debugging of communication between Java program and serial port

After the addition is completed, check it in the device manager and find that there are two more virtual serial ports, such as Picture:

Implementation and debugging of communication between Java program and serial port

Download the serial port debugging software http://pan.baidu.com/s/1c0AVaXq The debugging software provided here is relatively old, but it is still relatively easy to use. Just unzip it and click to open it.

You can directly open two debugging windows first, which are used to represent the COM3 and COM4 serial ports respectively. The parameters of the two serial ports must be set the same to send and receive data normally. (If debugging can send and receive data normally, you can turn off a debugger and use a java program instead) As shown in the figure:

Implementation and debugging of communication between Java program and serial port

java program code writing

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

Program code analysis:

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
    // 监听器,我的理解是独立开辟一个线程监听串口数据
    static CommPortIdentifier portId; // 串口通信管理类
    static Enumeration<?> portList; // 有效连接上的端口的枚举
    InputStream inputStream; // 从串口来的输入流
    static OutputStream outputStream;// 向串口输出的流
    static SerialPort serialPort; // 串口的引用
    // 堵塞队列用来存放读到的数据
    private BlockingQueue<String> msgQueue = new LinkedBlockingQueue<String>();

    @Override
    /**
     * SerialPort EventListene 的方法,持续监听端口上是否有数据流
     */
    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:// 当有可用数据时读取数据
            byte[] readBuffer = new byte[20];
            try {
                int numBytes = -1;
                while (inputStream.available() > 0) {
                    numBytes = inputStream.read(readBuffer);

                    if (numBytes > 0) {
                        msgQueue.add(new Date() + "真实收到的数据为:-----"
                                + new String(readBuffer));
                        readBuffer = new byte[20];// 重新构造缓冲对象,否则有可能会影响接下来接收的数据
                    } else {
                        msgQueue.add("额------没有读到数据");
                    }
                }
            } catch (IOException e) {
            }
            break;
        }
    }

    /**
     * 
     * 通过程序打开COM4串口,设置监听器以及相关的参数
     * 
     * @return 返回1 表示端口打开成功,返回 0表示端口打开失败
     */
    public int startComPort() {
        // 通过串口通信管理类获得当前连接上的串口列表
        portList = CommPortIdentifier.getPortIdentifiers();

        while (portList.hasMoreElements()) {

            // 获取相应串口对象
            portId = (CommPortIdentifier) portList.nextElement();

            System.out.println("设备类型:--->" + portId.getPortType());
            System.out.println("设备名称:---->" + portId.getName());
            // 判断端口类型是否为串口
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                // 判断如果COM4串口存在,就打开该串口
                if (portId.getName().equals("COM4")) {
                    try {
                        // 打开串口名字为COM_4(名字任意),延迟为2毫秒
                        serialPort = (SerialPort) portId.open("COM_4", 2000);

                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // 设置当前串口的输入输出流
                    try {
                        inputStream = serialPort.getInputStream();
                        outputStream = serialPort.getOutputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // 给当前串口添加一个监听器
                    try {
                        serialPort.addEventListener(this);
                    } catch (TooManyListenersException e) {
                        e.printStackTrace();
                        return 0;
                    }
                    // 设置监听器生效,即:当有数据时通知
                    serialPort.notifyOnDataAvailable(true);

                    // 设置串口的一些读写参数
                    try {
                        // 比特率、数据位、停止位、奇偶校验位
                        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("--------------任务处理线程运行了--------------");
            while (true) {
                // 如果堵塞队列中存在数据就将其输出
                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) {
            // 启动线程来处理收到的数据
            cRead.start();
            try {
                String st = "哈哈----你好";
                System.out.println("发出字节数:" + 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;
        }
    }
}

Java program and serial port communication debugging

Program debugging screenshots:

Implementation and debugging of communication between Java program and serial port

Summary

Serial port communication is used in many places, especially embedded development, SMS module development and for All kinds of hardware product customization software are needed. Among them, the most commonly used communication protocol is the RS-232 communication protocol. If you want to become a real serial communication development master, you need to fully understand the serial communication protocol (I am still a novice... I hope an expert can give guidance).

Another focus of serial communication is how to determine the type of data and extract valid data after receiving the data. These need to be coded according to the corresponding protocol.



For more articles related to communication implementation and debugging between Java programs and serial ports, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools