Using Java to implement serial communication _java

Source: Internet
Author: User
Tags gettext

1. Introduce

The use of Java-implemented serial communication program to support the sending and receiving of hexadecimal data.
SOURCE Download Address:

The effect chart is as follows:


Java serial communication-dependent jar package Rxtxcomm.jar
Download Address:

Contains 32-bit and 64-bit versions
How to use:
Copy Rxtxcomm.jar into the Java_home\jre\lib\ext directory;
Copy RxtxSerial.dll into the Java_home\jre\bin directory;
Copy RxtxParallel.dll into the Java_home\jre\bin directory;
Java_home Installation path for JDK

3. Serial Communication Management

Serialportmanager realizes the management of serial communication, including finding available ports, turning off the serial port and sending receiving data.

Package com.yang.serialport.manage;

Import java.util.ArrayList;
Import java.util.Enumeration;

Import java.util.TooManyListenersException;
Import Com.yang.serialport.exception.NoSuchPort;
Import Com.yang.serialport.exception.NotASerialPort;
Import Com.yang.serialport.exception.PortInUse;
Import Com.yang.serialport.exception.ReadDataFromSerialPortFailure;
Import Com.yang.serialport.exception.SendDataToSerialPortFailure;
Import Com.yang.serialport.exception.SerialPortInputStreamCloseFailure;
Import Com.yang.serialport.exception.SerialPortOutputStreamCloseFailure;
Import Com.yang.serialport.exception.SerialPortParameterFailure; Import com.yang.serialport.exception.tOomanylisteners;
 /** * Serial Port management * * @author Yangle/public class Serialportmanager {/** * Find all available ports * * * @return Available port Name list * * @SuppressWarnings ("unchecked") public static final arraylist<string> Findport () {//Get all current available serial ports enumeration<
  Commportidentifier> portlist = commportidentifier. Getportidentifiers ();
  arraylist<string> portnamelist = new arraylist<string> ();
   Adds an available serial port name to the list and returns the list while (Portlist.hasmoreelements ()) {String portname = Portlist.nextelement (). GetName ();
  Portnamelist.add (PortName);
 return portnamelist; /** * Open Serial Port * * @param portname * Port name * @param baudrate * baud rate * @return Serial object * @throws SerialPort 
  Parameterfailure * Set serial parameter failed * @throws Notaserialport * Port pointing device is not a serial port type * @throws Nosuchport * Does not have the port corresponding serial device * @throws Portinuse * port is occupied * * public static final SerialPort Openport (String portname, int baudrate) throw S serialportparameterfailure, notaserialPort, Nosuchport, Portinuse {try {//) identify ports via port name Commportidentifier Portidentifier = Commportidentifier. G
   Etportidentifier (PortName);
   Open the port, set the port name and timeout (timeout time for the open operation) Commport Commport = (PortName, 2000);
    The judge is not the serial if (Commport instanceof SerialPort) {SerialPort SerialPort = (SerialPort) commport; try {//Set the baud rate of the serial port Serialport.setserialportparams (baudrate, Serialport.databits_8, Serialport.stopbits_
    1, Serialport.parity_none);
    catch (Unsupportedcommoperationexception e) {throw new serialportparameterfailure ();
   return serialPort;
   else {//not serial throw new Notaserialport ();
  } catch (Nosuchportexception E1) {throw new Nosuchport ();
  catch (portinuseexception E2) {throw new Portinuse ();
  }/** * Close serial Port * * @param serialport * The serial object to be closed/public static void Closeport (SerialPort serialport) { if (serialPort!= null) {serialport.close ();
   SerialPort = null; /** * Send data to serial port * * @param serialPort * Serial Object * @param order * Data to be sent * @throws Senddatatoserialport Failure * Failed to send data to serial port * @throws serialportoutputstreamclosefailure * Shutdown Serial Object output error/public static void Sendt
  Oport (SerialPort SerialPort, byte[] order) throws Senddatatoserialportfailure, Serialportoutputstreamclosefailure {
  OutputStream out = null;
   try {out = Serialport.getoutputstream ();
   Out.write (order);
  Out.flush ();
  catch (IOException e) {throw new senddatatoserialportfailure ();
     Finally {try {if (out!= null) {out.close ();
    out = null;
   } catch (IOException e) {throw new serialportoutputstreamclosefailure (); /** * Reads data from serial port * * @param serialPort * Current Connected SerialPort Object * @return Read data * @throws READDATAFR  Omserialportfailure * Error reading data from serial port * @throws serialportinputstreamclosefailure * Close Serial object input out error/public static Byte[] ReaDfromport (SerialPort SerialPort) throws Readdatafromserialportfailure, Serialportinputstreamclosefailure {inputst
  Ream in = null;
  byte[] bytes = NULL;
   try {in = Serialport.getinputstream ();
   Gets the data length in buffer int bufflenth = in.available ();
    while (bufflenth!= 0) {//Initialize the byte array to the length of the data in buffer bytes = new Byte[bufflenth]; (bytes);
   Bufflenth = In.available ();
  } catch (IOException e) {throw new readdatafromserialportfailure ();
     Finally {try {if (in!= null) {in.close ();
    in = null;
   } catch (IOException e) {throw new serialportinputstreamclosefailure ();
 } return bytes; /** * Add Listener * * @param port * Serial Object * @param listener * Serial listener * @throws Toomanylisteners * Listening class pair
  Like too much */public static void AddListener (SerialPort port, Serialporteventlistener listener) throws Toomanylisteners {
   try {//Add listeners to the serial port Port.addeventlistener (listener);
Set up to wake up listening for incoming threads when data arrives   Port.notifyondataavailable (TRUE);
  Sets the thread Port.notifyonbreakinterrupt (true) to wake up when the communication is interrupted;
  catch (Toomanylistenersexception e) {throw new toomanylisteners ();

4. program main Window

* * * * * Created on 2016.8.19/package com.yang.serialport.ui;

Import Java.awt.Color;
Import java.awt.GraphicsEnvironment;
Import Java.awt.Point;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;

Import java.util.List;
Import Javax.swing.BorderFactory;
Import Javax.swing.JButton;
Import Javax.swing.JComboBox;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JPanel;
Import Javax.swing.JScrollPane;
Import Javax.swing.JTextArea;

Import Javax.swing.JTextField;
Import Com.yang.serialport.exception.NoSuchPort;
Import Com.yang.serialport.exception.NotASerialPort;
Import Com.yang.serialport.exception.PortInUse;
Import Com.yang.serialport.exception.SendDataToSerialPortFailure;
Import Com.yang.serialport.exception.SerialPortOutputStreamCloseFailure;
Import Com.yang.serialport.exception.SerialPortParameterFailure; Import Com.yang. serialport.exception.TooManyListeners;
Import Com.yang.serialport.manage.SerialPortManager;
Import Com.yang.serialport.utils.ByteUtils;

Import Com.yang.serialport.utils.ShowUtils; /** * Main interface * * @author yangle/public class MainFrame extends JFrame {/** * Program interface width/public static final

 T WIDTH = 500;

 /** * Program Interface Height * * public static final int height = 360;
 Private JTextArea DataView = new JTextArea ();

 Private JScrollPane Scrolldataview = new JScrollPane (DataView);
 Serial Port Setup Panel private JPanel serialportpanel = new JPanel ();
 Private JLabel Serialportlabel = new JLabel ("Serial port");
 Private JLabel Baudratelabel = new JLabel ("baud rate");
 Private JComboBox Commchoice = new JComboBox ();

 Private JComboBox Baudratechoice = new JComboBox ();
 Operator panel private JPanel operatepanel = new JPanel ();
 Private JTextField datainput = new JTextField ();
 Private JButton serialportoperate = new JButton ("Open serial port");

 Private JButton SendData = new JButton ("Send data"); Private list<string> COmmlist = null;

 Private SerialPort SerialPort;
  Public MainFrame () {Initview ();
  Initcomponents ();
  ActionListener ();
 InitData ();
  private void Initview () {//Close program setdefaultcloseoperation (Javax.swing.WindowConstants.EXIT_ON_CLOSE);

  Prevents window maximization setresizable (FALSE);
  The Set program window is centered to show point P = graphicsenvironment.getlocalgraphicsenvironment (). Getcenterpoint ();

  This.setlayout (NULL);
 Settitle ("serial communication");
  private void Initcomponents () {//Data display dataview.setfocusable (FALSE);
  Scrolldataview.setbounds (10, 10, 475, 200);

  Add (Scrolldataview);
  Serial port Set Serialportpanel.setborder (Borderfactory.createtitledborder ("Serial set"));
  Serialportpanel.setbounds (10, 220, 170, 100);
  Serialportpanel.setlayout (NULL);

  Add (Serialportpanel);
  Serialportlabel.setforeground (Color.gray);
  Serialportlabel.setbounds (10, 25, 40, 20);

  Serialportpanel.add (Serialportlabel);
Commchoice.setfocusable (FALSE);  Commchoice.setbounds (60, 25, 100, 20);

  Serialportpanel.add (Commchoice);
  Baudratelabel.setforeground (Color.gray);
  Baudratelabel.setbounds (10, 60, 40, 20);

  Serialportpanel.add (Baudratelabel);
  Baudratechoice.setfocusable (FALSE);
  Baudratechoice.setbounds (60, 60, 100, 20);

  Serialportpanel.add (Baudratechoice);
  Operation Operatepanel.setborder (Borderfactory.createtitledborder ("Operation"));
  Operatepanel.setbounds (200, 220, 285, 100);
  Operatepanel.setlayout (NULL);

  Add (Operatepanel);
  Datainput.setbounds (25, 25, 235, 20);

  Operatepanel.add (Datainput);
  Serialportoperate.setfocusable (FALSE);
  Serialportoperate.setbounds (45, 60, 90, 20);

  Operatepanel.add (serialportoperate);
  Senddata.setfocusable (FALSE);
  Senddata.setbounds (155, 60, 90, 20);
 Operatepanel.add (SendData);
  @SuppressWarnings ("unchecked") private void InitData () {commlist = Serialportmanager.findport (); Check to see if there are any available serial ports, then join option if (commlist = null | | commlist.size () < 1) {Showutils.warninGmessage ("No search to a valid serial port!")
   else {for (String s:commlist) {Commchoice.additem (s);
  } baudratechoice.additem ("9600");
  Baudratechoice.additem ("19200");
  Baudratechoice.additem ("38400");
  Baudratechoice.additem ("57600");
 Baudratechoice.additem ("115200"); private void ActionListener () {Serialportoperate.addactionlistener (new ActionListener () {@Override public V OID actionperformed (ActionEvent e) {if ("Open serial port". Equals (Serialportoperate.gettext ()) && SerialPort = = nul
    L) {OpenSerialPort (e);
    else {closeserialport (e);

  }); Senddata.addactionlistener (new ActionListener () {@Override public void actionperformed (ActionEvent e) {Sendda
   Ta (e);
  }); /** * Open Serial Port * * * @param evt * Click event/private void OpenSerialPort (Java.awt.event.ActionEvent evt) {//obtained
  The serial name string commname = (string) commchoice.getselecteditem ();
  Gets the baud rate int baudrate = 9600; String bps = (string) baudRatechoice.getselecteditem ();

  BaudRate = Integer.parseint (bps); Check to see if the serial name gets the correct if (Commname = null | | commname.equals ("")) {showutils.warningmessage ("No search to a valid serial port!")
    else {try {serialport = Serialportmanager.openport (Commname, baudrate);
     if (serialport!= null) {Dataview.settext ("serial port is turned on" + "\ r \ n");
    Serialportoperate.settext ("Close serial port");
   } catch (Serialportparameterfailure e) {e.printstacktrace ();
   catch (Notaserialport e) {e.printstacktrace ();
   catch (Nosuchport e) {e.printstacktrace ();
    catch (Portinuse e) {e.printstacktrace (); Showutils.warningmessage ("Serial port has been occupied!")
  } try {Serialportmanager.addlistener (SerialPort, New Seriallistener ());
  catch (Toomanylisteners e) {e.printstacktrace ();
  }/** * Close serial Port * * @param EVT * Click event/private void Closeserialport (Java.awt.event.ActionEvent evt) {
  Serialportmanager.closeport (SerialPort);
  Dataview.settext ("Serial port has been closed" + "\ r \ n"); SErialportoperate.settext ("Open serial port"); /** * Send Data * * @param EVT * Click event/private void SendData (Java.awt.event.ActionEvent evt) {//Input box Direct input
  hexadecimal characters, which must be even String data = Datainput.gettext (). toString ();
  try {serialportmanager.sendtoport (SerialPort, Byteutils.hexstr2byte (data));
  catch (Senddatatoserialportfailure e) {e.printstacktrace ();
  catch (Serialportoutputstreamclosefailure e) {e.printstacktrace (); } Private class Seriallistener implements Serialporteventlistener {/** * processing monitored serial events/public void Seriale Vent (serialportevent serialportevent) {switch (Serialportevent.geteventtype ()) {case SERIALPORTEVENT.BI://10 Pass
    Message Interrupt Showutils.errormessage ("With serial equipment communication Interruption");


   Case SERIALPORTEVENT.OE://7 overflow (overflow) error case SERIALPORTEVENT.FE://9 Frame Error Case SERIALPORTEVENT.PE://8 Parity Error Case SERIALPORTEVENT.CD://6 Carrier detection case SERIALPORTEVENT.CTS://3 Clear Pending Data case SERIALPORTEVENT.DSR://4 Pending data ready.

   Case SERIALPORTEVENT.RI://5 ringing indicates case serialportevent.output_buffer_empty://2 The output buffer has been emptied of the break;
    Case serialportevent.data_available://1 The serial port exists available data byte[], or null; try {if (SerialPort = null) {showutils.errormessage ("Serial Port object is empty!") Listening failed!
      else {//read serial port data = Serialportmanager.readfromport (SerialPort);
     Dataview.append (byteutils.bytearraytohexstring (data, true) + "\ r \ n");
     The catch (Exception e) {showutils.errormessage (e.tostring ());
    Exit the system system.exit (0) after displaying an error message when a read error occurs;
   } break; }} public static void Main (String args[]) {Java.awt.EventQueue.invokeLater (The new Runnable () {public void run (
   {New MainFrame (). setvisible (True);

5. Written in the final

SOURCE Download Address:

Students are welcome to spit comments, if you think this blog is useful to you, then leave a message or the top of it (^)

Thank you:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.