To write a program to control the serial communication, Java inside has ...

Source: Internet
Author: User
Tags stringbuffer
Understanding Serial Communications
There are many kinds of serial communication protocols, such as rs232,rs485,rs422, or even the current popular USB is serial
Communication protocols. And the application of serial communication technology is everywhere. Maybe everyone sees the computer serial and mode.
M's communication. Remember when the PC first began to catch on in China (about five years before the 90 's), when there were even
A man uses a serial line to share data between two computers. In addition to these, mobile phones, Pda,usb mouse, keyboard
And so on are connected to the computer in a serial communication mode. And the author of the nature of the relationship, the contact is more
, such as multi-port cards, all kinds of serial communication interface with the detection and measurement instruments, serial communication network equipment
Wait
Although there are many kinds of serial communication, but the author knows in the whole electronic communication products, to RS232 communication side
Most see. 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 process
Preface it.
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) was in 1970 by the American Electronics Association (E
IA) Joint Bell System, modem manufacturer, and computer terminal manufacturer for serial communication
Standard. RS232 is a Full-duplex communication protocol that can receive and send data at the same time. RS232
There are usually two types of ports: 9-pin (DB9) and 25-pin (DB25).
Common PIN definitions for DB9 and DB25
9-pin serial port (DB9)
25-pin serial port (DB25)

PIN number
Function description
Abbreviation 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 Terminal Preparation
DTR
5
Signal Land
GND 7
Signal Land
GND
6
Data Device ready.
DSR 6
Data ready.
Dsr
7
Request to send RTS 4
Request Send
Rts
8
Clear Send
CTS 5
Clear Send
Cts
9
Ringing indication
RI 22
Ringing indication
RI
A common sideline approach
A common form of communication is a three-wire approach, which is the sending end (TXD) and receiver (RXD) of two RS232 devices and
The grounding terminals (GND) are connected to each other and are known by many readers:


(9 stitches)
2 (RXD)-------3 (TXD
3 (TXD)-------2 (TXD)
5 (GND)-------5 (GND)
(25 stitches)
2 (RXD)-------3 (TXD
3 (TXD)-------2 (RXD)
7 (GND)-------7 (GND)
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 them
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
Department notebook the computer, it can be wired in this way. Three-wire can connect most of the RS232 devices
To. But if you do, you're dead. 2--3,3--2,5 (7)--5 (7) Docking this reason will find that when some RS232 devices are connected and
Doesn't work. This is because some of the equipment within the circuit has been 2 and 3 wire Exchange, you just 2,3,5 (7) Needle One
correspond on the line.
Tip: 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
As long as the voltage between the 2--5 or 3--5 pins of the RS232 port is measured separately, there is usually a 3 between txd pins and GND
The negative voltage around the ~15v indicates that it is a txd stitch.
Installing the Java Communications API
Sun's J2SE does not directly provide any of the above-mentioned serial communication protocol development package, but the
The form of the Jar package is published on the java.sun.com website (download from here)----namely Comm.jar, call it Javat
M Communications API, which is the standard extension of J2SE. Comm.jar not a recent, as early as 1998
, Sun has already released this development package. Comm.jar provides a common RS232 serial port and IEEE
1284 support for parallel port communications. Currently, Sun releases only two versions of Windows and Solaris platform Comm.jar
, if you need Linux under the platform, you can Http://www.geeksville.com/~kevinh/linuxcomm
. html found.
Before you can use Comm.jar, you must know how to install it. This is also troubling many beginners Java RS232 Newsletter
One of the difficulties of the people. If the JDK is installed on our computer, it will also install a JRE for us (Java Runtim
e entironment), usually we run 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 <JRE_HOME> to <JDK_HOME>.
After downloading the Comm.jar development package, there are two important files, Win32com.dll and Java
X.comm.properties. Comm.jar provides a Java API for communication, while Win32com.dll provides co
Mm.jar The local driver interface for the call. And Javax.comm.properties is the driver of this class configuration file. First of all
Copy the Comm.jar to the <jre_home>libext directory. and copy Win21com.dll to your RS232 application.
Sequence running directory, that is, User.dir. Then copy the javax.comm.properties to the <jre_home>lib directory

Pre-communication preparation
If you don't have a standard RS232 serial device available on hand, you can simulate your computer
Two different serial devices. Usually the panel behind the computer host provides two 9-pin serial port, please put these two serial ports
The 2,3,5 foot is connected by the method described earlier. The electronic market has ready-made connection head to sell, please do not buy that kind of package
Tight joints, and to buy with a screw package can be opened the connector, so that you can easily use the need to connect
Connect each stitch.
Comm API Basics
I am not interested in detailing the use of each class and interface of the Comm API here, but I will introduce the class knot of the Comm API
Construction 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
The following 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 column
Out of all available RS232 ports 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, each
The serial port corresponds to an instance of the 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
parameter, the first is string, and is usually set to the name of your application. The second parameter is time, which is open
The number of milliseconds that the port timed out. Portinuseexception exception is thrown when the port is occupied by another application

What's the difference between a Commportidentifier class and a Commport class here? In fact, they are both a pair
should be the relationship. Commportidentifier is primarily responsible for the initialization and opening of ports, and for managing their tenure
。 The commport is related to the actual input and output functions. Through the Commport getInputStream ()
The input stream of the port can be obtained, which is an instance of the Java.io.InputStream interface. We can use the standard
InputStream interface to read the data in the stream, just like reading the contents of a file through Fileinputsteam a
Sample. Accordingly, the Commport Getoutputstream can get the output stream of the port so that it can be lost to the serial ports.
Out of the data.
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 it
It may throw an error that the port is in use when it uses the port. It's strange, commportidenti.
The Fier class only provides a way to open the port, and to turn off the port, you call the Close () method of the Commport class.
Communication mode
The input stream of the Commport is different from the input stream of the file, which is that you may never know
When this inputstream ends, unless each other's outputstream sends you a specific data representation to send
End, after you receive this particular character, then line off your inputstream. and Comm.jar offers two kinds of flexible
Way to get you to read the data.
1. Polling mode (Polling)
For example, you and GF meet together to go out to see a movie, but your gf good dress up, this dress may be half
Hours or even more than an hour. At this point you will not be able to endure, every two minutes to urge to ask "well no." "And so this
Like, until your GF said OK to finish. 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. Just now
In that case, your GF said, "OK." "This is the condition that ends your poll. In a single-threaded program,
When a loop is always performing a task and cannot predict when it ends, your program may look like a dead
Machine. In VB program, this problem can be solved by inserting a doevent statement in the loop structure. and J
In Ava, the best way is to use a thread, 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. In other words, you can use a similar addxxxli
Stener such a method for a serial port registration of their own listeners, listening to the data read.
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 there is any Serialp
When an ORT event occurs, the Serialevent method in the listener is automatically invoked. Serial event has the following several
Type:
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 often
Care is the Data_available event that fires when data is transferred from an external device to the port. Now
You can use the previously mentioned method, Serialport.getinputstream () to read from the InputStream
Data.
The Complete program
To save space, this article only provides snippets of code to help readers understand the usage of the Comm API. You can
To obtain a complete, operational demo from the Comm API's development package. Please download the development kit for the Comm API first
, after decompression, there is a directory named Sample, which has several demo programs, namely:
1) blackbox:a serial Port blackbox application.
2) parallelblackbox:a Parallel Port blackbox Application
3) serialdemo:a Simpler SerialPort sample application
4) simple:a very simple Comm Application
5) nulldriver:a template for driver writers. Can be used as the starting PO
Int
To write a driver for the Comm API.
6) porting:a Template commportidentifier Java file for people interested
In porting the Comm API to a new platform.
of which, 1th, 3), 4 is a demo program for RS232 communication. The others, 2, are demo programs for parallel ports.
5 and 6) is the development of their own port driver template program, interested readers can study for themselves.
 
 
"In RJ
(RJ)
The masterpiece mentioned: ": Look at me a few days ago," the popularity of such a low, send a javax.comm everyone to learn.
:
:
: Java (TM) communications APIs for platform-independent communication applications such as voice mail, fax, and electrical
: A child card.
: The directory structure is as follows:
:. Interface Javax.comm.CommDriver
:. Class Javax.comm.CommPort
: Class Javax.comm.ParallelPort
: Class Javax.comm.SerialPort
: ................. (Omitted below)

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.