java serial communication details and simple examples

  • 2020-05-30 20:04:18
  • OfStack

java implements serial communication

Recently, I did a project related to hardware. At first, I heard that java was used to deal with hardware, so I really made a big jump. java can also operate hardware?

Later, I came into contact with java to control the hardware through serial communication. I felt that it was quite good and convenient to use it.

Take it out and share it with everyone.

Preparation:

First go to the SUN website to download one zip package: javacomm20-win32.zip

Important among them are the following documents:

win32com.dll

comm.jar

javax.comm.properties

Configure the environment according to the instructions, as follows:

Copy win 32com. dll to < JDK > \bin; Copy comm.jar to < JDK > \ lib; Copy javax.comm.properties as well < JDK > Item \lib directory. However, this is not enough when you are actually running with a serial package. This is because usually when running "java MyApp", MyApp is started by the virtual machine under JRE. We will only copy the above files to the appropriate directory of JDK, so the application will prompt that the serial port cannot be found. The solution to this problem is simple, we just need to put the files mentioned above in the corresponding directory of JRE

To this 1 can java serial port development environment is built

Confirm the serial port that the machine can use:


package test;

import java.util.Enumeration;
import java.util.HashMap;

import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;

public class GetSerialPorts {

  public void listPortChoices() {
    CommPortIdentifier portId;
    Enumeration en = CommPortIdentifier.getPortIdentifiers();
    // iterate through the ports.
    while (en.hasMoreElements()) {
      portId = (CommPortIdentifier) en.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        System.out.println(portId.getName());
      }
    }

  }

  public static void main(String[] args) {

    GetSerialPorts GSP = new GetSerialPorts();
    GSP.listPortChoices();

  }

}



Open the serial port and close the serial port:


package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;

public class GetSerialPorts {

  private CommPortIdentifier portId;

  private SerialPort testPort;

  private CommPortIdentifier myPort;

  private InputStream is;

  private OutputStream os;

  public void listPortChoices() {

    Enumeration en = CommPortIdentifier.getPortIdentifiers();
    // iterate through the ports.
    while (en.hasMoreElements()) {
      portId = (CommPortIdentifier) en.nextElement();
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
        System.out.println(portId.getName());
      }
      myPort = portId;//  arbitrary 1 A serial port, for example com1
    }

  }

  public boolean openPort() {
    try {
      testPort = (SerialPort) myPort.open("COM1", 500);//  Notice I have to replace it here 1 A real serial port 
      try {
        this.testPort.setSerialPortParams(38400, SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1, SerialPort.PARITY_EVEN);
      } catch (UnsupportedCommOperationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      try {
        this.testPort.enableReceiveTimeout(30);
      } catch (UnsupportedCommOperationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      this.testPort.setOutputBufferSize(1024);
      this.testPort.setInputBufferSize(1024);

      try {
        this.is = this.testPort.getInputStream();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      try {
        this.os = this.testPort.getOutputStream();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      this.testPort.notifyOnDataAvailable(true);
      this.testPort.notifyOnOutputEmpty(true);
      this.testPort.notifyOnBreakInterrupt(true);

      // this.printerPort.addEventListener(new PrintPortListener(is));
      System.out.println(" Open the com1 Machine serial port successful ");
      return true;
    } catch (PortInUseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return false;
    }

  }

  /**
   * TODO  Close port 
   * 
   * @param
   * @return Map
   * @throws
   */
  public boolean closePort() {
    // TODO Auto-generated method stub
    try {
      if (null != this.testPort) {
        is.close();
        os.close();
        this.testPort.close();
      }
      System.out.println(" Shut down COM1 A serial port success ");
      return true;
    } catch (Exception e) {
      // TODO Auto-generated catch block
      // e.printStackTrace();
      System.out.println(" Shut down COM1 A serial port failure ");
      return false;
    }
  }

  public static void main(String[] args) {

    GetSerialPorts GSP = new GetSerialPorts();
    GSP.listPortChoices();
    GSP.openPort();

  }

}

Read data:


/**
   * TODO  Receiving port 
   * 
   * @param InputStream
   * @return String
   * @throws
   */
  public String readData(InputStream is) {
    //  Read buffer area 
    byte[] readBuffer = new byte[4096];
    int readDataLength = 0;
    try {
      readDataLength = is.read(readBuffer);
      // for (byte b : readBuffer) {
      // System.out.print(b);
      // }
      // System.out.println();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
    //  Saves real data into a zero-time array 
    byte[] readTemp = new byte[readDataLength];
    for (int i = 0; i < readDataLength; i++) {
      readTemp[i] = readBuffer[i];
    }

    //  will byte Array to 16 Base string 
    String stringTemp = FeelTheBase.bytesToHexString(readTemp);
    // System.out.println(" Instruction return value " + stringTemp);

    return stringTemp;

  }


Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: