This article shares the specific code for Java to implement serial communication for your reference. The specific content is as follows
1. Introduction
The serial communication program implemented by Java supports the sending and receiving of hexadecimal data.
Source code: SerialPortDemo
The renderings are as follows:
2.RXTXcomm
Java serial communication dependency jar package RXTXcomm.jar
Download address: http://download.csdn.net/detail/kong_gu_you_lan/9611334
Includes 32-bit and 64-bit version usage:
Copy RXTXcomm.jar to 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 is the jdk installation path
3. Serial port communication management
SerialPortManager implements the management of serial port communication, including finding available ports, opening and closing the serial port, and sending and receiving data.
package com.yang.serialport.manage;import gnu.io.CommPort;import gnu.io.CommPortIdentifier;import gnu.io.NoSuchPortException;import gnu.io.PortInUseException;import gnu.io.SerialPort;import gnu.io.SerialPortEventListener;import gnu.io.UnsupportedCommOperationException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;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 List of available port names*/ @SuppressWarnings("unchecked") public static final ArrayList<String> findPort() { // Get all currently available serial ports Enumeration<CommPortIdentifier> portList = CommPortIdentifier .getPortIdentifiers(); ArrayList<String> portNameList = new ArrayList<String>(); // Add the available serial port name to the List and return 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 port object* @throws SerialPortParameterFailure * Failed to set serial port parameters* @throws NotASerialPort * Port pointing to the device is not the serial port type* @throws NoSuchPort * No serial port device corresponding to this port* @throws PortInUse * Port has been occupied*/ public static final SerialPort openPort(String portName, int baudrate) throws SerialPortParameterFailure, NotASerialPort, NoSuchPort, PortInUse { try { // Identify port by port name CommPortIdentifier portIdentifier = CommPortIdentifier .getPortIdentifier(portName); // Open the port, set the port name and timeout (timeout time of opening operation) CommPort commPort = portIdentifier.open(portName, 2000); // Determine whether it is a serial port if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort; try { // Set the baud rate and other parameters 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 the serial port throw new NotASerialPort(); } } catch (NoSuchPortException e1) { throw new NoSuchPort(); } catch (PortInUseException e2) { throw new PortInUse(); } } /** * Close the serial port* * @param serialport * Serial port object to be closed*/ public static void closePort(SerialPort serialPort) { if (serialPort != null) { serialPort.close(); serialPort = null; } } /** * Send data to the serial port* * @param serialPort * Serial port object* @param order * Data to be sent* @throws SendDataToSerialPortFailure * Failed to send data to the serial port* @throws SerialPortOutputStreamCloseFailure * Close the output streaming error of the serial port object*/ public static void sendToPort(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(); } } } /** * Read data from the serial port* * @param serialPort * The SerialPort object with the currently established connection* @return The data read* @throws ReadDataFromSerialPortFailure * An error occurred while reading data from the serial port* @throws SerialPortInputStreamCloseFailure * An error occurred when closing the serial port object input stream*/ public static byte[] readFromPort(SerialPort serialPort) throws ReadDataFromSerialPortFailure, SerialPortInputStreamCloseFailure { InputStream in = null; byte[] bytes = null; try { in = serialPort.getInputStream(); // Get the data length int in the buffer bufflenth = in.available(); while (bufflenth != 0) { // Initialize the byte array to the length of data in the buffer bytes = new byte[bufflenth]; in.read(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 port object* @param listener * Serial port listener* @throws TooManyListeners * TooManyListeners * TooManyListener too many listening class objects*/ public static void addListener(SerialPort port, SerialPortEventListener listener) throws TooManyListener { try { // Add listener port.addEventListener(listener); // Set the wake-up listening receiving thread when data arrives port.notifyOnDataAvailable(true); // Set the wake-up interrupt thread when communication is interrupted port.notifyOnBreakInterrupt(true); } catch (TooManyListenersException e) { throw new TooManyListeners(); } }}4. Program main window
/* * MainFrame.java * * Created on 2016.8.19 */package com.yang.serialport.ui;import gnu.io.SerialPort;import gnu.io.SerialPortEvent;import gnu.io.SerialPortEventListener;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.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 int WIDTH = 500; /** * Program interface height*/ public static final int HEIGHT = 360; private JTextArea dataView = new JTextArea(); private JScrollPane scrollDataView = new JScrollPane(dataView); // Serial port settings panel private JPanel serialPortPanel = new JPanel(); private JLabel serialPortLabel = new JLabel("serial port"); private JLabel baudrateLabel = new JLabel("baudrate"); private JComboBox commChoice = new JComboBox(); private JComboBox baudrateChoice = new JComboBox(); // Operation 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 the program setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); // Forbid window maximization setResizable(false); // Set the program window to center Point p = GraphicsEnvironment.getLocalGraphicsEnvironment() .getCenterPoint(); setBounds(px - WIDTH / 2, py - HEIGHT / 2, WIDTH, HEIGHT); this.setLayout(null); setTitle("Serial Communication"); } private void initComponents() { // Data display dataView.setFocusable(false); scrollDataView.setBounds(10, 10, 475, 200); add(scrollDataView); // SerialPortPanel.setBorder(BorderFactory.createTitledBorder("SerialPortset")); 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.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 if there is a serial port, add it to the option if (commList == null || commList.size() < 1) { ShowUtils.warningMessage("No valid serial port was found! "); } 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 void actionPerformed(ActionEvent e) { if ("Open serial port".equals(serialPortOperate.getText()) && serialport == null) { openSerialPort(e); } else { closeSerialPort(e); } } }); sendData.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendData(e); } }); } /** * Open serial port* * @param evt * Click event*/ private void openSerialPort(java.awt.event.ActionEvent evt) { // Get the serial port name String commName = (String) commChoice.getSelectedItem(); // Get the baud rate int baudrate = 9600; String bps = (String) baudrateChoice.getSelectedItem(); baudrate = Integer.parseInt(bps); // Check whether the serial port name is correct if (commName == null || commName.equals("")) { ShowUtils.warningMessage("No valid serial port was found! "); } else { try { serialport = SerialPortManager.openPort(commName, baudrate); if (serialport != null) { dataView.setText("Serialport is turned on" + "/r/n"); serialPortOperate.setText("Close serialport"); } } catch (SerialPortParameterFailure e) { e.printStackTrace(); } catch (NoSuchPort e) { e.printStackTrace(); } catch (PortInUse e) { e.printStackTrace(); ShowUtils.warningMessage("The serial port has been occupied!"); } } try { SerialPortManager.addListener(serialport, new SerialListener()); } catch (TooManyListeners e) { e.printStackTrace(); } } /** * Close the serial port* * @param evt * Click event*/ private void closeSerialPort(java.awt.event.ActionEvent evt) { SerialPortManager.closePort(serialport); dataView.setText("Serial port is closed" + "/r/n"); serialPortOperate.setText("Open serial port"); } /** * Send data* * @param evt * Click event*/ private void sendData(java.awt.event.ActionEvent evt) { // Enter hexadecimal characters directly in the input box, the length 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 { /** * Handle monitored serial port events*/ public void serialEvent(SerialPortEvent serialPortEvent) { switch (serialPortEvent.getEventType()) { case SerialPortEvent.BI: // 10 Communication interrupt ShowUtils.errorMessage("Communication interrupt with serial device"); break; 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 data to be sent case SerialPortEvent.DSR: // 4 The data to be sent case SerialPortEvent.RI: // 5 Ring indication case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2 The output buffer has been cleared break; case SerialPortEvent.DATA_AVAILABLE: // 1 Available data exists on the serial port byte[] data = null; try { if (serialport == null) { ShowUtils.errorMessage("The serial port object is empty! Monitoring failed! "); } else { // Read serial port data data = SerialPortManager.readFromPort(serialport); dataView.append(ByteUtils.byteArrayToHexString(data, true) + "/r/n"); } } catch (Exception e) { ShowUtils.errorMessage(e.toString()); // Exit the system after displaying an error when a read error occurs System.exit(0); } break; } } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); }}5.Written at the end
Source code download address: SerialPortDemo
Students are welcome to complain and comment. If you think this blog is useful to you, then leave a message or give it a comment (^-^)
Thanks: Writing serial communication tools based on Java
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.