Understand serial communication
A variety of 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 Foundation
RS-232-C (also known as EIA RS-232-C, hereinafter referred to as RS232) is used by the US Electronics Industry Association (EIA) combined with Bell system, modem manufacturers and computer terminal manufacturers for 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
figure 1
Common side line
Common communication methods are three-wire, this way is to connect two RS232 devices to each other, and a connection method known to many readers:
figure 2
This approach connects 2-3, 3 --- 2, 5 (7) - 5 (7) pins of the two ends of the RS232 interface. 2 is the data receiving line (RXD), 3 is the data transmission line (TXD), 5 (7) is a grounding (RND). If there is a PC, and a Notebook computer, you can connect it with this way. Most RS232 devices can be connected with a three-wire. But if you recognize 2-3, 3-2,5 (7) - 5 (7), it will find that it does not work when some RS232 devices are connected. This is because some equipment has been transferred to the 2 and 3 lines inside the circuit, and you only have 2, 3, 5 (7) the need for one or 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.
Install Java Communications API
The SUN J2SE did not directly provide any of the developments of the serial communication protocol mentioned above, but released on the Java.sun.com website in the form of a separate JAR package (download from here) --- Comm.jar, called Javatm Communications API, which 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, please change it accordingly.
.
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 your comm.jar to
/ lib / EXT directory. Copy Win21com.dll to your RS232 application running directory, ready for User.dir. Then copy javax.comm.properties to
/ 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 devices. 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.
COMM API foundation
I have not intentionally 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.ParalLPort
Javax.comm.SerialPort
Javax.comm.commportIdentifier
Javax.comm.commportownershiplistener
Javax.comm.ParalLPortevent
Javax.comm.SerialPortevent
Javax.comm.ParalLPortEventListener (Extends Java.util.EventListener)
Javax.comm.SerialPorteventListener (Extends Java.util.EventListener)
Javax.comm.nosuchportException
Javax.comm.PortinuseException
javax.comm.unsupportedCommoprationException
Let's explain a few major or interfaces.
1. Enumerate all RS232 ports
Before starting using RS232 port communication, we want to know which ports are available, and the following code lists all available RS232 ports in the system:
Enumeration en = commportidentifier.getportidentifier.getPortIndIndiFiers ();
CommPortidentifier portid;
While (en.hasmoreElements ())
{
Portid = (CommPortidentifier) En.nexTelement ();
/ * If the port type is a serial port, the port information is printed * /
IF (portid.getporttype () == comMmportidentifier.port_serial
{
System.out.println (portid.getname ());
}
Out the following results on my computer:
Com1
COM2
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 the port
If you use port, you must open it first.
Try {
CommPort serialport = portid.open ("My App", 60);
/ * Read data from port * /
InputStream INPUT = SerialPort.getInputStream ();
INPUT.READ (...);
/ * Write data in the port * /
OutputStream output = serialport.getOutputStream ();
Output.write (...)
...
} catch (portinuseexception ex)
{...}
A CommPort object can be returned by 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. Turn off the port
After using the port, you must remember to turn it off, so that other programs have the opportunity to use it, otherwise, other programs may throw the ports 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.
communication method
Comm port's input stream is somewhat different from the input stream of the file, that is, you may never know when this InputStream ends, unless the other's OutputStream is sent to you, you receive this specific character. After, close your InputStream. Comm.jar provides two flexible ways to let you read data.
Polling method (polling)
For 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 Mode (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.
If you want to listen to the port, you must first get an instance of the CommPortIndIfier class.
CommPort serialport = portid.open ("My App", 60);
This makes SerialPort, then calls its AddEventListener method to add a listener.
SerialPort.Addeventlistener (New MyportListener ());
The SERIALPORT's listener must be inherited in 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 interruption.
CD - carrier detection.
CTS - Clear Send.
Data_available - has data arrival.
DSR - data equipment is ready.
Fe - frame error.
OE - overflow error.
Output_buffer_empty - The output buffer is clear.
PE - parity.
Ri - ringing instructions.
Below is an example of a listener:
Public Void MyportListener Implements SerialPorteventListener
{
Public void seriavent (SerialPortEvent EVT)
{
Switch (evt.geteventtype ())
{
Case SerialPortevent.ct.ct.ct.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.output_buffer_empty:
System.out.println ("Output_Buffer_empty Event Occured.");
Break;
Case SerialPortevent.Data_available:
System.out.println ("DATA_AVAILABLE Event Occured.");
int CH;
StringBuffer buf = new stringbuffer ();
InputStream Input = SerialPort.getInputStream
Try {
While ((ch = INPUT.READ ())> 0) {
BUF.Append ((char) ch);
}
System.out.print (buf);
} catch (ioexception 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.