Java Serial Port Communication

xiaoxiao2021-03-06  45

There are many kinds of serial communication serial communication protocols, like RS232, RS485, RS422, and even today's popular USB, etc. are serial communication protocols. The application of serial communication technology is everywhere. It may be the most important to see the computer's serial port and modem. I remember that when the PC was just prevalent in China (approximately five years before the 1990s), then there were even a serial line to perform data sharing between two computers. In addition to these, mobile phones, PDAs, USB mouse, keyboard, etc. are connected to computers with serial communication. And the relationship between the work of the author, more, like multi-serial card, various types of detection and measuring instruments, serial communication network equipment, etc. Although serial communication has many kinds, the author knows that the RS232 communication is most common in the entire electronic communication product. Although the electronic product of the USB interface is also endless, it is understood that Java is necessary in serial communication technology, saying that the reader wants to use this technology to write a PDA and the computer data shared between the PDA. This paper mainly explains the serial communication technology of Java in the Lord of RS232. RS232 Communication Basic RS-232-C (also known as EIA RS-232-C, hereinafter referred to as RS232) is used in 1970 by the US Electronics Industry Association (EIA) combined with Bell system, modem manufacturers and computer terminal manufacturers Serial communication standard. RS232 is a full-duplex communication protocol that can simultaneously perform data reception and delivery. The port of RS232 usually has two: 9-pin (DB9) and 25 pins (DB25). Common pin definitions of DB9 and DB25

9-pin serial port (DB9) 25-pin serial port (DB25) pin number function Description shrink pin number function Description Abbreviation 1 Data carrier detection DCD 8 data carrier detection DCD 2 Receive data RXD 3 Receive data RXD 3 Send data TXD 2 Send data TXD 4 data Terminal Preparation DTR 20 Data Term Preparation DTR 5 Signal GND 7 Signal GND 6 Data Device Preparation DSR6 Data Preparation DSR 7 Request Send RTS 4 Request Send RTS 8 Clear Send CTS 5 Clear Send CTS 9 Ring Indication Ri 22 Ring The communication method that indicates that the common side line mode of Ri is three-wire, which is connected to each other of the transmitting end (TXD) and receiving end (RXD) and ground terminals (GND) of the two RS232 devices, as well as many readers known. Connection method: (9 pins)

2 (RXD) --------- 3 (TXD3 (TXD) --------- 2 (TXD) 5 (GND) --------5 (GND) ( 25-pin)

2 (rxd) --------- 3 (TXD3 (TXD) --------- 2 (RXD) 7 (GND) --------- 7 (GND) The 2-3, 3-- 2,5 (7) - 5 (7) pins of both ends of the RS232 interface are connected separately. 2 is the data receiving line (RXD), 3 is a data transmission line. (TXD), 5 (7) is a grounding (RND). If there is a PC, and a Notebook computer can be connected in this way. With a three-wire, most of the RS232 devices can be connected. But if You recognize 2-3, 3--2, 5 (7) - 5 (7), will find that it does not work when connecting some RS232 devices. This is because some equipment has been in the circuit The 2 and 3 lines are turned over, and you only have to correspond one by one, and you will do one by one.

Tips: How to distinguish TXD and RXD ports? People who engage in electronics should always have a meter, used to measure the voltage, and what the resistance will be useful. You only need to measure the voltage between the 2-5 or 3-5 pins of the RS232 port, usually there is a negative voltage of about 3 to 15V between the TXD pin and the GND, indicating that it is a TXD pin. The J2SE installed in Java Communications API SUN did not directly provide any of the developments mentioned above, but released on a separate JAR package (download from here) (download from here) - --- Comm.jar, called Javatm Communications API, is a standard extension of J2SE. Comm. Jar is not recently, as early as 1998, Sun has released this development package. Comm. JAR provides support for common RS232 serial port and IEEE1284 parallel port. Current SUN released only two versions of Windows and Solaris platforms, if you need Linux platform, you can find it at http://www.geeksville.com/~kevinh/linuxcomm.html. Before using Comm. Jar, you must know how to install it. This is also a problem that plagues many java RS232 communications. If our computer is installed on the computer, it will install a JRE (Java Runtime Entironment), usually run with JRE when we run the program. So the following installation applies to JRE. If you use JDK to run the program, change the corresponding to . After downloading the comm.jar development package, there are two important files with one, Win32com.dll, and javax.comm.properties. Comm.jar provides a Java API for communication, while Win32com.dll provides a local driver interface for COMM.jar calls. Javax.comm.properties is this driver class profile. First copy the comm.jar to the / lib / ext directory. Copy Win21com.dll to your RS232 application running directory, ready for User.dir. Then copy javax.comm.properties to the / lib directory. Preparation before communication If you have no ready-made devices that offer standard RS232 serial ports on your hand, you can simulate your own computer into two different serial ports. Usually the panel behind the computer host provides two 9-pin serial port, connect the two serial ports 2, 3, 5 pins to the method described earlier. There are ready-made connections for the electronic market. Please do not buy the tightly realistic connector of the package, and to buy a screw package can be opened, so it can be convenient to connect each pin as needed. The COMM API basis I unintentionally describe the usage of each class and interface, but I will introduce the class structure and several important API usage of the COMM API. All COMM API is located below the Javax.comm package. From the Javadoc from the Comm API, it introduces us 13 or interfaces below the zone:

javax.comm.CommDriver javax.comm.CommPort javax.comm.ParallelPort javax.comm.SerialPort javax.comm.CommPortIdentifier javax.comm.CommPortOwnershipListenerjavax.comm.ParallelPortEvent javax.comm.SerialPortEvent javax.comm.ParallelPortEventListener (extends java.util. EventListener) javax.comm.SerialPortEventListener (extends java.util.EventListener) javax.comm.NoSuchPortException javax.comm.PortInUseException javax.comm.UnsupportedCommOperationException below explain several major class or interface. 1. Enumerate all RS232 ports before starting to use the RS232 port communication, we want to know which ports are available, the following code lists all available RS232 ports in the system:

Enumeration en = CommPortIdentifier.getPortIdentifiers (); CommPortIdentifier portId; while (en.hasMoreElements ()) {portId = (CommPortIdentifier) ​​en.nextElement (); / * If the port is a serial type, which prints out the port information * / if ( Portid.getPortType () == CommportIdentifier.port_serial) {system.out.println (portid.getname ());}} In my computer, the above program outputs the following results: Com1COM2

The GetPortIndifiers method for the CommPortIndiFier class can find all the serial ports of the system, each serial port corresponding to an instance of a CommPortIndifier class. 2. Open port If you use port, you must open it first. Try {CommPort SerialPort = Portid.Open ("My App", 60); / * Read Data from the Port * / InputStream Input = SerialPort.GetinputStream (); Input.Read (...); / * During the port Write data * / outputstream output = serialport.getOutputStream (); output.write (...) ...} catch (portinuseException ex) {...} You can return a commport object with the Open method of CommPortIndifier. The Open method has two parameters, the first one is String, usually set to your application name. The second parameter is time, that is, the number of milliseconds that turn on the port. When the port is occupied by another application, the portinuseexception exception will be thrown. What is the difference between the CommPortIndifier class and the COMMPORT class? In fact, both are the corresponding relationships. CommPortidentifier is primarily responsible for port initialization and opening, as well as managing their share. CommPort is related to the actual input and output function. GetInputStream () through CommPort can get the input stream of the port, which is an instance of the java.io.inputstream interface. We can read the data in the current data with standard InputStream operation interfaces, just like reading the files read by FileInputSteam. Correspondingly, CommPort's GetOutputStream can get the port output stream so that data can be output to serial port. 3. Close the port used in the port, you must remember to turn it off, which allows other programs to have the opportunity to use it, otherwise, other programs may throw an error in use when using this port. It is very strange that the CommMportIdentifier class only provides a way to turn on port, and the port is turned off, then call the CLOSE () method of the CommPort class. The communication method of Comm port is a bit different from the input stream of the file, that is, you may never know when this INPUTSTREAM ends, unless the other's OutputStream sends a specific data to send the end, you receive this After a specific character, close your InputStream. Comm.jar provides two flexible ways to let you read data. 1. Polling is given an example, you go to the movie with GF, but your GF is good, this dress may be half an hour or more. At this time, you can't stop it. Every two minutes will ask "good?", So, until your GF said OK is over. This is called polling. In the program, polling is typically designed to end cycles when a certain condition is satisfied. In that case, your GF said "OK!", This is the condition that ends you poll. In a single-threaded program, when the loop has been executed and cannot predict when it ends, your program seems to be like a crash. In the VB program, this problem can be used in inserting a DOEVENT statement in a loop structure.

In Java, the best way is to use threads, just like the following code snippet. public TestPort extend Thread {... InputStream input = serialPort.getInputStream (); StringBuffer buf = new StringBuffer (); boolean stopped = false; ... public void run () {try {while (! stopped) int ch = input .read (); if (CH == 'q' || CH == 'q') {/ * End Read, close the port ... * / stopped = true; ...} else {buf.Append (CHAR) CH); ...}} Catch (InterruptedException E) {}}} 2. Listening COMM API supports standard Java Bean-type event models. That is, you can use a method similar to addXXXListener to register your own listener for a serial port to read in a monitor mode. To listen to the port, you must first get an instance of the CommPortIndiFier class, command serialport = portid.open ("My App", 60); thus get SerialPort, then call its AddEventListener method to add a listener, serialport.addeventListener (New myportListener ()); SERIALPORT listener must inherit the SerialPorteventListener interface. When any SerialPort occurs, the serialEvent method in the listener will be automatically called. Serial Event has the following types: BI - communication interrupt. CD - carrier detection .cts - Clear Send .DATA_AVAILABLE - Data arrived. DSR - Data device ready. FE - frame error .oe - Sluit error .output_buffer_empty - output The buffer has been emptied .pe - parity. Ri - ringing indication.

The following is an example of a listener, public void MyPortListener implements SerialPortEventListener {public void serialEvent (SerialPortEvent evt) {switch (evt.getEventType ()) {case SerialPortEvent.CTS: System.out.println ( "CTS event occured."); Break; Case SerialPortevent.cd: System.Out.println ("CD Event Occured."); Break; Case SerialPortevent.bi: System.out.println ("Bi Event Occured."); Break; Case SerialPortevent.dsr: System .out.println ("DSR Event Occured."); Break; Case SerialPortevent.fe: System.Out.println ("Fe Event Occured."); Break; Case SerialPortevent.oe: System.out.println ("OE Event Occured. "); Break; Case SerialPortevent.pe: System.out.println (" Pe Event Occured. "); Break; Case SerialPortevent.ri: System.out.println (" Ri Event Occured. "); Break; Case SerialPortevent.out PUT_BUFFER_EMPTY: System.out.println ( "OUTPUT_BUFFER_EMPTY event occured."); Break; case SerialPortEvent.DATA_AVAILABLE: System.out.println; int ch; StringBuffer buf = new StringBuffer (); InputStream input ( "DATA_AVAILABLE event occured.") = SerialPort.GetinputStream try {while ((ch = INPUT ())> 0) {buf.append ((char) ch);} system.out.print (buf);} catch (ooException e) {} BREAK This listener just simply prints each incident name. For most applications, it is usually concerned that this event will be triggered when data is transmitted from external devices to the port.

At this point, you can use the method mentioned above, serialPort.getInputStream () to read data from the InputStream. A complete program provides a savings, this article only provides some code snippet to help readers understand the usage of the Comm API. You can get a complete runoffs from the developing package of the CommSi. I would like to download the developing package of the Comm API, there is a directory named sample, there are several demonstrations, namely: 1) Blackbox: a seriallelblackbox: a Parallel Port Blackbox Application3) SerialDemo: A simpler SerialPort sample application4) Simple: A very simple comm application5) NullDriver:. A template for driver writers Can be used as the starting pointto write a driver for the Comm API.6) porting: A template CommPortIdentifier java file for people INTERESTEDIN PORTING THE COMM API TO A New Platform.

Among them, 1st, 3), 4) are demo procedures for communication with the RS232. And other, 2) is a demonstration program for parallel ports. 5) and 6) are template programs for developing their port drivers, and interested readers can study themselves.

转载请注明原文地址:https://www.9cbs.com/read-56251.html

New Post(0)