Java Serial Port Technology protocol

Source: Internet
Author: User
Tags copy connect stringbuffer
Understanding Serial Communications

There are many kinds of serial communication protocols, such as rs232,rs485,rs422, even the popular USB is serial communication protocol. And the application of serial communication technology is everywhere. Perhaps everybody sees most is the computer serial port and the modem communication. Remember when the PC was first popular in China (about five years before the 90 's), when someone even used a serial line to share data between two computers. In addition to these, the mobile phone, Pda,usb mouse, keyboard, etc. are connected to the computer in the way of serial communication. And the author of the nature of the relationship, the contact is more, like many serial cards, all kinds of serial communication interface with the detection and measurement instruments, serial communication network equipment.

Although there are many kinds of serial communication, but I know the whole electronic communication products, the most RS232 communication methods. Although the USB interface of electronic products are endless, but to understand the Java in the serial communication technology is also necessary, perhaps a reader who would like to use this technology to write a PDA and computer data sharing program.

This article mainly to RS232 to explain the Java serial communication technology.

RS232 Communication Basics

Rs-232-c (also known as EIA Rs-232-c, hereinafter referred to as RS232) is a standard for serial communications developed in 1970 by the United States Electronics Association (EIA) Joint Bell System, modem manufacturers and computer terminal manufacturers. RS232 is a Full-duplex communication protocol that can receive and send data at the same time. There are usually two types of RS232 ports: 9-pin (DB9) and 25-pin (DB25).

Common PIN definitions for DB9 and DB25



Figure 1

A common sideline approach

A common form of communication is a three-wire approach, which connects the sender (TXD) and the receiver (RXD) and the grounding (GND) of two RS232 devices to the connections that many readers know:



Figure 2

In this way, the 2--3,3---2,5 (7)---5 (7) Pins of the RS232 interface between the two ends are connected respectively. 2 of which is the data receiving line (RXD), 3 is the data transmission line (TXD), 5 (7) is grounded (RND). If you have a desktop PC and a notebook computer, you can connect it in this way. The three-wire type can be used to connect most of the RS232 devices. But if you do, you're dead. 2--3,3--2,5 (7)--5 (7) Docking this reason will find that it does not work in connection with some RS232 devices. This is because some of the equipment within the circuit has been 2 and 3 lines, you just 2,3,5 (7) A pair of pins should be on the line.

Tips: How to identify Txd and RXD ports?

Electronic people should have a power meter on hand to measure the voltage, resistance or whatever will be useful. You only need to measure the voltage between the 2--5 or the 3--5 pins of the RS232 port, usually txd between the pins and the GND will have a negative voltage of about 3~15v, indicating that it is a txd stitch.


Installing the Java Communications API

Sun's J2SE does not directly provide any of the above mentioned in the development of a serial communication protocol, but instead in the form of a separate jar package published on the java.sun.com Web site (download from here)----that is Comm.jar, called JavaTM Communications API, which is the standard extension of J2SE. Comm.jar was not a recent one, and as early as 1998, Sun had already released the development package. Comm.jar provides support for commonly used RS232 serial ports and IEEE1284 parallel port communications. At the moment, Sun releases only two versions of Windows and Solaris platforms, and if you need Linux Comm.jar, you can find them in http://www.geeksville.com/~kevinh/linuxcomm.html.

Before you can use Comm.jar, you must know how to install it. This is also a problem that puzzles many beginners Java RS232 Communicator. If the JDK is installed on our computer, it will also install a JRE (Java Runtime entironment) for us, usually running the program as a JRE. So the following installation applies to the JRE. If you are using JDK to run the program, please change the corresponding.

After downloading the Comm.jar development package, there are two important files, 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. And Javax.comm.properties is the driver of this class configuration file. First copy the Comm.jar to the \lib\ext directory. Then copy the Win21com.dll to the directory where your RS232 application runs, that is, User.dir. Then copy the javax.comm.properties to the \lib directory.

Pre-communication preparation

If you don't have a standard RS232 serial device available on hand, you can simulate your computer into two different serial devices. Usually the panel behind the computer host provides two 9-pin serial ports, please connect the 2,3,5 feet of the two serial ports by the method described above. The electronic market has ready-made connection head to sell, please do not buy that kind of packing of the tight fittings, but buy to use the screw to seal can open the connector, so that you can easily connect each stitch as needed.

Comm API Basics

I have no intention of detailing the use of each class and interface of the Comm API here, but I will introduce the class structure of the Comm API and several important API usages.

All Comm APIs are located under the Javax.comm package. From the Comm API's Javadoc, it introduces us to only a few 13 classes or interfaces:

Javax.comm.CommDriver

Javax.comm.CommPort

Javax.comm.ParallelPort

Javax.comm.SerialPort

Javax.comm.CommPortIdentifier

Javax.comm.CommPortOwnershipListener

Javax.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


Here are a few main classes or interfaces.

1. Enumerate all the RS232 ports of the system

Before we start using RS232 Port communications, we want to know which ports are available on the system, and the following code lists all the RS232 ports available in the system:

Enumeration en = Commportidentifier.getportidentifiers ();

Commportidentifier Portid;

while (En.hasmoreelements ())

{

Portid = (commportidentifier) en.nextelement ();

/* If the port type is serial, print out its port information.

if (portid.getporttype () = = commportidentifier.port_serial)

{

System.out.println (Portid.getname ());

}

}

On my Computer The above program outputs the following results:

COM1

COM2

The Getportidentifiers method of Commportidentifier class can find all the serial ports of the system, and each serial port corresponds to an instance of Commportidentifier class.

2. Open port

If you use a port, you must first open it.

try{

Commport SerialPort = Portid.open ("My App", 60);

/* Read data from the port * *

InputStream input = Serialport.getinputstream ();

Input.read (...);

* * Write data to Port

OutputStream output = Serialport.getoutputstream ();

Output.write (...)

...

}catch (Portinuseexception ex)

{ ... }

You can return a Commport object by using the Commportidentifier open method. The open method has two parameters, the first is string, and is usually set to the name of your application. The second parameter is the time, that is, the number of milliseconds to open the port timeout. A Portinuseexception exception is thrown when the port is occupied by another application.

What is the difference between Commportidentifier class and Commport class here? In fact, they are one by one corresponding relationship. Commportidentifier is primarily responsible for the initialization and opening of ports, as well as managing their tenure. The commport is related to the actual input and output functions. The input stream of the port can be obtained through the Commport getInputStream (), which is an instance of the Java.io.InputStream interface. We can read the data in the stream using the standard InputStream interface, just as the contents of the file are read by Fileinputsteam. Accordingly, the Commport Getoutputstream can get the output stream of the port, so that the data can be exported to the serial port.

3. Close the port

The port you have used must remember to turn it off so that other programs will have the opportunity to use it, or else programs using that port may throw errors that are in use by the port. Oddly enough, the Commportidentifier class only provides a way to open the port, and to close the port, call the Commport class's closing () method.


Communication mode

The input stream of Commport is different from the input stream of the file, that is, you may never know when this inputstream is over, unless the other party's outputstream sends you a specific data indicating that the sending end, after you receive this particular character, Then you can close your inputstream. and Comm.jar provides two flexible ways for you to read data.

1. Polling mode (Polling)

For example, you and GF meet together to go out to see a film, but your gf good dress up, this dress may be half an hour or even more than an hour. Then you can't stand it, ask once every two minutes. "So, until your gf says OK is finished." This is called polling (Polling).

In a program, polling is usually designed as a closed loop that ends the loop when a condition is met. In that example, your GF said, "OK!" "This is the condition that ends your poll. In a single-threaded program, your program may look like a crash when the loop has been performing a task and cannot predict when it will end. In VB program, this problem can be solved by inserting a doevent statement in the loop structure. In Java, the best way is to use threads, just like the following code fragment.

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 port ... * *

stopped = true;

...

}

Else

{

Buf.append ((char) ch);

...

}

}catch (Interruptedexception e) {}

}

}

2. Monitoring mode (listening)

The Comm API supports the standard Java bean-type event model. That is, you can use a method like Addxxxlistener to register your listener for a serial port and read the data in a listening mode.

To monitor the port, you must first obtain an instance of the Commportidentifier class,

Commport SerialPort = Portid.open ("My App", 60);

To get SerialPort, and then call its AddEventListener method to add listeners to it,

Serialport.addeventlistener (New Myportlistener ());

SerialPort listeners must inherit from the Serialporteventlistener interface. When any SerialPort event occurs, the Serialevent method in the listener is automatically invoked. The serial event has the following types:

BI-Communication interrupted.

CD-carrier detection.

CTS-Clear send.

Data_available-there is data arriving.

DSR-Data Equipment ready.

FE-Frame error.

OE-Overflow error.

Output_buffer_empty-The output buffer is empty.

PE-Parity error.

RI-ringing indicator.

   

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.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 simply prints each event name that occurs. For most applications, however, it is usually a matter of data_available events that are triggered when data is transferred from an external device to a port. You can now read the data from the InputStream using the previously mentioned method, Serialport.getinputstream ().




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: info-contact@alibabacloud.com 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.