Recently due to the needs of the project, the need to use the Java serial port and Windows-side Java program Communication, the author is just contact with the serial port of this module, in the online search for a lot of serial programming examples and so on, almost all the previous article, but the configuration before the serial communication is very important, if the configuration is not successful, Programming also seems meaningless. Serial programming has two main interfaces, the first is the use of sun-provided Comm.jar package, this way is more ancient, this package has not been updated. The second is the RXTX mode, which is almost the same as the pattern of the Comm.jar package. The following is a note of my record of learning and using this module. RXTX Resource Bundle, there are many online, but to note is to look at your computer configuration, if it is Win64-bit system, you want to download RXTX 64-bit Resource pack, otherwise error.
(1) Setup and configuration of programming environment
This article is based on the RXTX (provide serial port and the communication of the same port) Open source class library to operate the serial port. Ready to use (Java_home here is the installation path of my JDK)
1. Place the Rxtxcomm.jar under%java_home%\jre\lib\ext\, such as: E:\jdk\Java1.8\jdk1.8.0_45\jre\lib\ext, or Item 1. Right-click->2.preperties ( Preferences)->3.java Build path->4.libraries->5.add External Jars introduced (we recommend using the latter one, which is sometimes not read in the project, If the JRE is not packaged in the project package, the project will not be successful when it is migrated to another device.
2. Put the rxtxSerial.dll into the%java_home%\jre\bin, such as: E:\jdk\Java1.8\jdk1.8.0_45\jre\bin, or C:\windows\system32
(2)RXTX Introduction
RXTX is an open source Java class Library that provides serial and port communication, and the files published by the project follow the LGPL protocol.
The RXTX project provides the implementation of a compatible Javax.comm serial communication packet API under the WINDOWS,LINUX,MAC OS X,solaris operating system, providing considerable convenience for other developers to develop serial port applications under such systems.
The use of RXTX is basically the same as the Comm.jar provided by Sun, and the most obvious difference in programming is that the package name to be included is changed from javax.comm.* to gnu.io.*
The core of Rxtxapi is the abstract Commport class, which describes an abstract class of ports supported by the underlying system, and contains some high-level IO control methods that are common to all different communication ports. And its two subclasses: the SerialPort class and the Paralleport class. Among them, the SerialPort class is the class used for serial communication, and the Paralleport class is the class used for parallel port communication. The Commport class also provides general communication patterns and methods, such as the getInputStream () method and the Getoutputstream () method, which are designed to communicate with devices on the port.
However, the construction methods of these classes are intentionally set to non-public (non-public). So, instead of directly constructing the object, we first get a list of ports by Static commportidentifer.getportidentifiers (), select the desired port from the port list, and call the Commportidentifer object's Open () method, so that a Commport object can be obtained. Of course, the type of the Commport object is also converted to a non-abstract subclass, indicating that it is a specific communication device, which can be one of the SerialPort class and the Paralleport class. The following will be the Commportidentifier class, serial port class SerialPort for detailed introduction.
Interface
Commdriver part of the loadable device driver interface
Commportownershiplistener passing ownership events for various communication ports
Parallelporteventlistener Passing parallel port events
Serialporteventlistener Passing serial port events
Class
Commport Communication Port
Commportidentifier Communication port Management
Parallelport Parallel Communication Port
Parallelportevent Parallel Port Events
SerialPortRS-232 Serial communication port
Serialportevent Serial Port Events
Exception class
Nosuchportexception thrown when the driver cannot find the specified port
Portinuseexception thrown when it encounters a specified port in use
Unsupportedcommoperationexception driver does not allow the specified operation to be thrown
Commportidentifier class
This class is primarily used to manage and set up communication ports and is the core class for access control of ports, mainly including the following methods:
Addportname (String,int, commdriver) add port name to Port list
Addportownershiplistener (Commportownershiplistener) Add a port-owned listener
Removeportownershiplistener (Commportownershiplistener) Remove the listener owned by the port
Getcurrentowner () Gets the object or application that currently occupies the port
GetName () Gets the port name
Getportidentifier (Commport) Gets the Commportidentifier type object for the specified open port
Getportidentifier (String) Gets the Commportidentifier type object for the port named by the parameter
Getportidentifiers () Get the list of ports in the system
Getporttype () Gets the type of the port
Iscurrentlyowned () determines whether the current port is occupied
Open (FileDescriptor) opens the port with the type described by the file
Open (String,int) opening port, two parameters: program name, delay time (number of milliseconds)
SerialPort class
This class is used to describe the underlying interface of a RS-232 serial communication port, which defines the minimum feature set required for serial communication. Through it, the user can directly to the serial port to read, write and set up work.
Description of static member variables for serial port parameters in the SerialPort class:
Databits_5 Data bits are 5
Databits_6 Data bits are 6
Databits_7 Data bits are 7
Databits_8 Data bits are 8
Parity_none Space Test
Parity_odd Odd Test
Parity_even-I test
Parity_mark Marking Test
Parity_space No test
Stopbits_1 Stop bit is 1
Stopbits_2 Stop bit is 2
Stopbits_1_5 Stop bit is 1.5
Description of the method for serial port parameters in the SerialPort class:
Getbaudrate () Get baud rate
Getparity () Get test type
Getdatabits () Gets the number of data bits
Getstopbits () Get stop digit
Setserialportparams (int,int, int, int) set serial port parameters in order (baud rate, data bit, stop bit, parity)
Description of the static member variable about the event in the SerialPort class:
BI Break Interrupt Communication Interrupt
FE Framing Error Frame errors
CD Carrier detect Carrier Listening
OE Overrun Error Overflow errors
CTS clear to send clear send
PE Parity Error Parity errors
The DSR data Set ready device
RI Ring Indicator ringing detection
Data_available available data in a string
Output_buffer_empty Output buffer is empty
Description of the method for the event in the SerialPort class:
ISCD () whether there is a carrier
Iscts () is cleared to transfer
ISDSR () data is ready
ISDTR () is the data terminal ready
IsRI () Whether ringing detection
Isrts () Whether the transfer is required
AddEventListener (Serialporteventlistener) Add serial event listener to SerialPort object
RemoveEventListener () Removing the serial event listener from the SerialPort object
Notifyonbreakinterrupt (Boolean) Set interrupt event True valid, False invalid
Notifyoncarrierdetect (Boolean) Set Carrier listener event True valid, False invalid
Notifyoncts (Boolean) setting clears send event true valid, False invalid
Notifyondataavailable (Boolean) Set serial port with data event True valid, False invalid
NOTIFYONDSR (Boolean) Setting data preparation event True valid, False invalid
Notifyonframingerror (Boolean) Setting Error event True valid, False invalid
Notifyonoutputempty (Boolean) set send buffer to NULL event true valid, False invalid
Notifyonparityerror (Boolean) setting occurs parity Error event true valid, False invalid
Notifyonringindicator (Boolean) Set ring detection event True valid, False invalid
Geteventtype () Gets the event type that occurs the return value is of type int
Sendbreak (int) Sets the time for the interrupt process, with a millisecond value for the parameter
Setrts (Boolean) set or clear RTS bit
SETDTR (Boolean) to set or clear the DTR bit
Other common method descriptions in SerialPort:
Close () Turn off the serial port
Getoutputstream () gets the output stream of the OutputStream type
getInputStream () gets the input stream of the InputStream type
(3) List the serial port and other communication port classes and methods, the following post demo
Import Java.util.enumeration;import java.util.hashset;import gnu.io.commport;import gnu.io.CommPortIdentifier; Import Gnu.io.portinuseexception;public class Listport {/** * @Description: List all available serial ports * @author:d Engchaoqun * @date: 2015-8 -29 a.m. 11:34:04 */public static void Listports () {hashset<commportidentifier> PortSet = Getavailableserialports (); for (Commportidentifier comm:portset) {System.out.println (Comm.getname () + "-" + Getporttypename (Comm.getporttype ())) ;}} /** * @Description: List all communication ports * @author:d Engchaqun * @date: 2015-8-29 pm 2:06:17 */@SuppressWarnings ("unchecked") public static void Listcommports () {commportidentifier.getportidentifiers ();/* * Getportidentifiers method without parameters can get an enumeration object, This object contains the Commportidentifier object for each port in the system. Note that the port here is not just the serial, but also the interface. * This method can also take parameters, Getportidentifiers (commport) Get the Commportidentifier object that corresponds to the port * already opened by the application. Getportidentifier (String portname) * Gets the Commportidentifier object for the specified port name (such as "COM1"). */java.util.enumeration<commportidentifier> Portenum = commportidentifier.gEtportidentifiers (); while (Portenum.hasmoreelements ()) {Commportidentifier portidentifier = portenum.nextelement (); System.out.println (Portidentifier.getname () + "-" + Getporttypename (Portidentifier.getporttype ());}} /** * @Description: Get communication Port Type name * @author: Lu * @date: 2015-8-29 am 11:35:32 */public static String getporttypename (int Porttyp e) {switch (portType) {case CommPortIdentifier.PORT_I2C:return "i²c"; case Commportidentifier.port_parallel:// Return "Parallel", Case CommPortIdentifier.PORT_RAW:return "RAW", Case commportidentifier.port_rs485:// RS485 Port return "RS485"; case commportidentifier.port_serial://serial return "SERIAL";d efault:return "Unknown type";}} /** * @Description: Get all available serial port collections * @author:d Engchaoqun * @date: 2015-8-29 morning 11:37:54 */@SuppressWarnings ("unchecked") public static hashset<commportidentifier> Getavailableserialports () {hashset<commportidentifier> h = new Hashset<commportidentifier> (); enumeration<commportidentifier> portlist = CommportidentifiEr.getportidentifiers (); while (Portlist.hasmoreelements ()) {commportidentifier com = (commportidentifier) Portlist.nextelement (); switch (Com.getporttype ()) {case CommPortIdentifier.PORT_SERIAL:try {//Open: (Application name "arbitrarily named", The number of milliseconds to wait while blocking)/* Open method opens the communication port, obtains a Commport object, it makes the program exclusive port. * If the port is being occupied by another application, a port_ownership_requested event will be passed using the Commportownershiplistener event mechanism *. * Each port is associated with a inputstream and a outputstream, if the port is opened with the * open method, then any getinputstream will return the same data stream object unless there is a close called. */commport Theport = Com.open (Object.class.getSimpleName (); Theport.close (); H.add (COM);} catch (Portinuseexception e) {//Not available serial System.out.println ("port," + com.getname () + ", is in use.");} catch (Exception e) {System.err.println ("Failed to open port" + com.getname ()); E.printstacktrace ();}} return h;} public static void Main (string[] args) {/** * can list all available serial port names for the current system, native output com1-serial, com2-serial ..... Com6-serial */listports (); Listcommports ();}}
(4) Debug serial input and output demo
Import Java.io.ioexception;import java.io.inputstream;import Java.io.outputstream;import Java.util.Date;import Java.util.enumeration;import Java.util.toomanylistenersexception;import Gnu.io.commportidentifier;import Gnu.io.portinuseexception;import Gnu.io.serialport;import Gnu.io.serialportevent;import Gnu.io.serialporteventlistener;import Gnu.io.unsupportedcommoperationexception;public class SerialPortTest1 Implements Runnable, Serialporteventlistener {///detection system available in the communication port class private Commportidentifier portid;//enumeration type Private enumeration<commportidentifier> portlist;//RS232 serial port private SerialPort serialport;//input/output stream private InputStream Inputstream;private outputstream outputstream;//Save serial port return information private String test = "";//Singleton Create private static SerialPortTest1 U Niqueinstance = new SerialPortTest1 ();//Initialize serial port @suppresswarnings ("unchecked") public void init () {// Get all communication ports in the system portlist = Commportidentifier.getportidentifiers ();//cyclic communication port while (Portlist.hasmoreelements ()) {Portid = Portlist.nextelement ();// Determine if the serial port if (portid.getporttype () = = commportidentifier.port_serial) {//compares the serial port name as "COM3" if ("COM2". Equals ( Portid.getname ()) {System.out.println ("Find serial COM2");//Open serial port try {//Opening: (Application name "Random name", number of milliseconds to wait on blocking) SerialPort = ( SerialPort) Portid.open (Object.class.getSimpleName (), 2000); System.out.println ("Get to Serial Port object, COM2");//Instantiate input stream inputstream = Serialport.getinputstream ();// Set Serial monitor Serialport.addeventlistener (this),//Set serial data time is valid (can listen) serialport.notifyondataavailable (TRUE);//Set serial communication parameters// Baud rate, data bit, stop bit and check mode//baud rate 2400, parity serialport.setserialportparams (9600, Serialport.databits_8,//serialport.stopbits_1 , Serialport.parity_none);} catch (Portinuseexception e) {e.printstacktrace ();} catch (Toomanylistenersexception e) {e.printstacktrace ();} catch ( Unsupportedcommoperationexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}} Implement the method in interface Serialporteventlistener read data received from a string @overridepublic void Serialevent (Serialportevent event) {switch ( Event.geteventtype ()) {case SERIALPORTEVENT.BI:// Communication Interrupt Case SERIALPORTEVENT.OE://Overflow error case SERIALPORTEVENT.FE://Frame Error case serialportevent.pe://Parity Error Case Serialporteven T.CD://Carrier detection case serialportevent.cts://Clear Send case SERIALPORTEVENT.DSR://Data Device Ready case SERIALPORTEVENT.RI://Bell Detection case Ser Ialportevent.output_buffer_empty://output buffer emptied break;case serialportevent.data_available://Data reached Readcomm (); Default:break;}} Read serial return information public void Readcomm () {byte[] Readbuffer = new Byte[1024];try {InputStream = Serialport.getinputstream ();//Slave line The road reads the data stream int len = 0;while (len = Inputstream.read (readbuffer))! =-1) {System.out.println ("Live feedback:" + new String (Readbuffer, 0, Len). Trim () + new Date ()), Test + = new String (readbuffer, 0, Len). Trim (); SYSTEM.OUT.PRINTLN (Test + "");//closeserialport ();} catch (IOException e) {e.printstacktrace ();}} public void Closeserialport () {uniqueInstance.serialPort.close ();} Send data to the serial port public void sendmsg () {String information = "at\r"; try {//Instantiate output stream outputstream = Serialport.getoutputstream ();} catch (IOExceptionE1) {e1.printstacktrace ();} try {outputstream.write (information.getbytes ());} catch (IOException e) {e.printstacktrace ();}} @Overridepublic void Run () {init (); sendmsg ();}}
(5) test the above input and output demo
public class Testdemo {public static void main (string[] args) {thread thread=new thread (new SerialPortTest1 ()); Thread.sta RT ();}}
The effect of serial test
(6) The following is the application of this demo to the project, the actual situation, according to their own needs to set
Java Serial Programming