Java Serial Communication

Source: Internet
Author: User
Java serial port communication API description Java serial port communication
Java serial communication API description

Java Serial Communication

Java provides the communicationapi (included in the javax. Comm package) for controlling various external devices in a machine-independent manner. Communications API is an extension of standard Java, which is not included in Java API. Therefore, you must first download this extension class library from the Java site (www.java.sun.com) on the sun website.

1.1 Introduction to communications API

The core of the communications API is the abstract comport class and its two sub-classes: SerialPort class and paralleport class. Among them, the SerialPort class is used for serial communication, and the paralleport class is used for parallel port communication. The comport class also provides common communication modes and methods, such as the getinputstream () and getoutputstream () methods, which are used to communicate with devices on the port.

However, the constructor methods of these classes are intentionally set to non-public ). Therefore, you cannot directly construct an object, but first use the static commp ortidentifer. getportidentifiers () is used to obtain the port list. Then, select the required port from the port list and call the open () method of the commp ortidentifer object. Of course, you also need to convert the type of the comport object to a non-Abstract subclass, indicating that it is a specific communication device. This subclass can be one of the SerialPort class and paralleport class. The following describes the comatrix, comatrix, and serial port types in detail.

1.2 commp ortidentifier class

The methods of the commp ortidentifier class are as follows:

Method description
Addportname (string, Int, commdriver): add the port name to the port list.
Addportownershiplistener (commp ortownershiplistener) add listener owned by the port
Removeportownershiplistener (commp ortownershiplistener) removes listener owned by the port
Getcurrentowner () obtains the object or application that currently occupies the port.
Get the port name by getname ()
Getportidentifier (comport) obtains the comportidentifier type object of the port opened by the parameter.
Getportidentifier (string) is used to obtain the commp ortidentifier type object of the port named after the parameter.
Getportidentifiers () to obtain the list of ports in the system
Getporttype () indicates the port type.
Iscurrentlyowned () checks whether the current port is occupied
Open (filedescriptor) open the port with the type described in the file
Open (string, INT) Open Port, two parameters: program name, delay time (milliseconds)

1.3 SerialPort class

SerialPort static member variables about serial port Parameters
Description of member variables description of member variables
Databits_5 data bit: 5 stopbits_2 stop bit: 2 parity_odd odd Test
Databits_6 data bit: 6 stopbits_1 stop bit: 1 parity_mark mark Test
Databits_7 data bit is 7 stopbits_00005 stop is 1.5 parity_none Space Test
Databits_8 data bit: 8 parity_even even test parity_space no test
SerialPort object functions related to serial port Parameters
Method description
Getbaudrate () Get the baud rate getparity () Get the test Type
Getdatabits () Get the data bits getstopbits () Get the Stop bits
Setserialportparams (INT, Int, Int, INT) sets the serial port parameters to (baud rate, data bit, stop bit, parity check) in sequence)
SerialPort static member variables about the event
Description of member variables
Error in Fe framing error interrupted by Bi break interrupt
CD carrier detect carrier listening OE overrun Error
CTS clear to send PE parity error parity check error
DSR data set ready data backup Ri ring indicator ring Detection
Available data output_buffer_empty output buffer in data_available serial port is empty
Event method in SerialPort
Method description
Iscd () whether the carrier iscts () is cleared to transmit isdsr () data is prepared
Isdtr () indicates whether the data end has prepared ISRI () and whether isrts () requires Transmission
Addeventlistener (serialporteventlistener) adds a serial event listener to the SerialPort object
Removeeventlistener () removes the serial event listener from the SerialPort object.
Notifyonbreakinterrupt (Boolean) is valid when the interrupt event is set to true, and false is invalid.
Notifyoncarrierdetect (Boolean) is valid when the carrier listening event is set to true, and false is invalid.
Valid yoncts (Boolean) is set to true to clear sending events, and false to be invalid.
Notifyondataavailable (Boolean) is valid when an event with data in the serial port is set to true, and false is invalid.
Notifyondsr (Boolean) sets the data preparation event to true and false.
Notifyonframingerror (Boolean) is set to true when an error occurs. False is invalid.
Notifyonoutputempty (Boolean) is valid if the sending buffer is null and false is invalid.
Notifyonparityerror (Boolean) is valid when a parity check error event is set to true, and false is invalid.
Notifyonringindicator (Boolean) is valid when the alarm detection event is set to true, and false is invalid.
Geteventtype () returns the int type as the event type.
Sendbreak (INT) specifies the duration of the interrupt process. The parameter value is millisecond.
Setrts (Boolean) sets or clears the RTS bit
Setdtr (Boolean) set or clear DTR bit
Other common methods in SerialPort
Method description
Close () Close the serial port
Getoutputstream () gets the output stream of the outputstream type.
Getinputstream () obtains the inputstream input stream.

 

 

Iv. Instances

 

I. Download
Go to its official homepage http://java.sun.com/products/javacomm/to download this API. The latest version is 3.0. However, it is a pity that sun has not released this API version 3.0 on the Windows platform. The three versions listed on the home page are the Solaris systems running on the x86 and iSCSI architectures, and x86 Linux systems. To download the Windows version, you can only search for older versions. The 2 URLs I have found are http://llk.media.mit.edu/projects/cricket/software/javaSerial.zip (two folders containing the three files needed), http://mdubuc.freeshell.org/jolt/javacomm20-win32.zipand (complete version 2.0, and examples ).
Ii. Installation
The so-called installation here is to put three important files under the specified directory.
After extracting the downloaded file, there are three required files under the/javacomm20-win32/commapi Directory: comm. jar, javax. Comm. properties, and win32comm. dll. Upload the file comm. jar copy to % java_home %/JRE/lib/EXT; file javax. comm. copy properties to % java_home %/JRE/LIB; file win32comm. copy the DLL to % java_home %/bin. Note that % java_home % is the JDK path, not the JRE.

 

First, let's look at the simplest read and write programs.
Serial Port reading routine

Import java. Io .*;
Import java. util .*;
Import javax. Comm .*;

Public class simpleread implements runnable, serialporteventlistener {
Static commp ortidentifier portid;
// Enumeration class
Static enumeration portlist;

Inputstream;
SerialPort;
Thread readthread;

Public static void main (string [] ARGs ){
Portlist = commp ortidentifier. getportidentifiers ();
/* Obtain an enumeration object using the getportidentifiers method without parameters. This object also contains the commp ortidentifier object for managing each port in the system.
Note that the port here is not only a serial port, but also a parallel port. This method can also contain parameters. Getportidentifiers
The commp ortidentifier object corresponding to the port opened by the program. Getportidentifier (string portname) to obtain the specified port name (for example, "COM1 ")
. */
While (portlist. hasmoreelements ()){
Portid = (comatrix ortidentifier) portlist. nextelement ();
/* The getporttype method returns the port type */
If (portid. getporttype () = comatrix ortidentifier. port_serial ){
/* Find the first serial port in Windows */
If (portid. getname (). Equals ("COM1 ")){
/* Find the first serial port in the Unix-like system */
// If (portid. getname (). Equals ("/dev/Term/")){
Simpleread reader = new simpleread ();
}
}
}
}

Public simpleread (){
Try {
/* Open the communication port in the open method to obtain a comport object. It excludes the program port. If the port is occupied by another application
The commp ortownershiplistener event mechanism transmits a port_ownership_requested event. Each port is associated with one
Inputstream and an outputstream. If the port is opened using the open method, any getinputstream will return
The same data flow object unless close is called. There are two parameters, the first is the application name; the second parameter is enabled on the port
The number of milliseconds for blocking. */
SerialPort = (SerialPort) portid. Open ("simplereadapp", 2000 );
} Catch (portinuseexception e ){}
Try {
/* Get the input stream object of the port */
Inputstream = SerialPort. getinputstream ();
} Catch (ioexception e ){}
Try {
/* Register a serialporteventlistener event to listen to the serial port event */
SerialPort. addeventlistener (this );
} Catch (toomanylistenersexception e ){}
/* Data availability */
SerialPort. yonyondataavailable (true );
Try {
/* Set the serial port initialization parameters, which are baud rate, data bit, stop bit, and verification */
SerialPort. setserialportparams (9600,
SerialPort. databits_8,
SerialPort. stopbits_1,
SerialPort. parity_none );
} Catch (unsupportedcommoperationexception e ){}
Readthread = new thread (this );
Readthread. Start ();
}

Public void run (){
Try {
Thread. Sleep (20000 );
} Catch (interruptedexception e ){}
}
// Serial events
Public void serialevent (serialportevent event ){
Switch (event. geteventtype ()){
Case serialportevent. BI:/* break interrupt, communication interruption */
Case serialportevent. OE:/* overrun error, overflow error */
Case serialportevent. Fe:/* Framing error, frame transfer error */
Case serialportevent. PE:/* parity error, verification error */
Case serialportevent. CD:/* carrier detect, carrier detection */
Case serialportevent. CTS:/* clear to send, clear send */
Case serialportevent. DSR:/* data set ready, data device ready */
Case serialportevent. Ri:/* Ring indicator, ring indicator */
Case serialportevent. output_buffer_empty:/* output buffer is empty, and the output buffer is cleared */
Break;
Case serialportevent. data_available:/* data available at the serial port. The port has available data. Read the buffer array and output it to the terminal */
Byte [] readbuffer = new byte [20];
Char [] readchar = new char [20];
String readstr = "";
Int numbytes = 0;
Try {
While (inputstream. Available ()> 0 ){
Numbytes = inputstream. Read (readbuffer );
}
For (INT IIi = 0; III <numbytes; III ++ ){
Readstr = readstr + byte. tostring (readbuffer [III]);
}
System. Out. println (readstr. Length ());
System. Out. println (readstr );
} Catch (ioexception e ){}
Break;
}
}
}

Serial Port writing routine
Import java. Io .*;
Import java. util .*;
Import javax. Comm .*;

Public class simplewrite {
Static enumeration portlist;
Static commp ortidentifier portid;
Static string messagestring = "Hello, world! /N ";
Static SerialPort;
Static outputstream;

Public static void main (string [] ARGs ){
Portlist = commp ortidentifier. getportidentifiers ();

While (portlist. hasmoreelements ()){
Portid = (comatrix ortidentifier) portlist. nextelement ();
If (portid. getporttype () = comatrix ortidentifier. port_serial ){
If (portid. getname (). Equals ("COM1 ")){
// If (portid. getname (). Equals ("/dev/Term/")){
Try {
SerialPort = (SerialPort)
Portid. Open ("simplewriteapp", 2000 );
} Catch (portinuseexception e ){}
Try {
Outputstream = SerialPort. getoutputstream ();
} Catch (ioexception e ){}
Try {
SerialPort. setserialportparams (9600,
SerialPort. databits_8,
SerialPort. stopbits_1,
SerialPort. parity_none );
} Catch (unsupportedcommoperationexception e ){}
Try {
Outputstream. Write (messagestring. getbytes ());
} Catch (ioexception e ){}
}
}
}
}
}

The preceding two routines are simplified. After the port is opened and the data stream and serial port are not closed after the transmission is complete. In the routine, we can see
You can open the communication port in the "open communication port" method provided by comatrix ortidentifier, but there is no corresponding method to close the port. to close the port, you need to call
Use close () of the javax. Comm. commp ORT class (). Comatrix is an advanced abstraction in this package, which defines various ports.
Condition: Get the I/O Data Stream object, control the buffer size, and adjust the input processing.

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.