[java] simply send a piece of data to the serial port

You can follow along with it.

2 Add an external jar to the project (with eclipse and intellij IDE operation instructions) 2.1 Suppose you use eclipse这里写图片描述



2.2 Using intellij这里写图片描述




3 add dll Copy the dll file to the bin directory of jdk and jre这里写图片描述


4 code

package Test180914;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;public class Test180914 {

    / / Simple way to send a piece of data to the serial port
    Public static void main(String[] args) {

        / / enumeration type, get all the access ports, including232(PORT_SERIAL)、485, parallel port, etc.
        Enumeration enumeration= CommPortIdentifier.getPortIdentifiers();

        while (enumeration.hasMoreElements()){
            / / Determine whether there are more elements in the enumeration

            / / Get the next element, which contains all the information of a communication port
            CommPortIdentifier commPortIdentifier=
                    (CommPortIdentifier) ​​enumeration.nextElement();//If the port type is serial
            If (commPortIdentifier.getPortType()==CommPortIdentifier.PORT_SERIAL){

                / / Determine the name of the serial port
                If (commPortIdentifier.getName().equals("COM2")){
                    Try {
                        / / Open the serial port, get the serialPort object of the serial port
                        SerialPort serialPort=
                                (SerialPort) commPortIdentifier.open("",2000);//Set the serial port parameters,9600,8,1,n
                        serialPort.setSerialPortParams(9600,8,1,0);//Get the output stream and send the data using the output stream
                        OutputStream outputStream=serialPort.getOutputStream();
                        outputStream.write("Hello World!".getBytes());//Be sure to close the serial port, otherwise it will block the serial port until you close the program

                    } catch (PortInUseException e) {
                        System.out.println("PortInUseException thrown, serial port is used");
                    } catch (UnsupportedCommOperationException e) {
                        System.out.println("UnsupportedCommOperationException throws ");
                    } catch (IOException e) {
                        System.out.println("IOException throw");

5 effects Use virtual serial port software to short COM1 and COM2, open the serial port assistant, open serial port 1, run the code to receive the data sent by the program.这里写图片描述