Using javax. Comm in Windows to read and write serial ports

Source: Internet
Author: User
Using javax. Comm in Windows to read and write serial ports

About javax. Comm
Javax. Comm is an extension API provided by Sun for developing independent communication applications on the platform. (PS: Here, javax's X accurately shows that it is an extension package, rather than a core package. But for historical reasons, not all of javax's extension packages are, for example, swing packages are already part of Java's core architecture. However, to be compatible with Java coding, javax is still used. swing .) Javax. Comm can access the RS232 interface (serial port) and access the IEEE-1284 (Parallel Port) with limited access ).

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

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

API
In javax. Comm, there are 13 classes and interfaces, which are

Four Interfaces
Part of the loadable Device Driver Interface
Commp ortownershiplistener transmits ownership events of various communication ports
Parallelporteventlistener transmits parallel port events
Serialporteventlistener transmits a serial port event

Six classes
Comport Communication Port
Commp ortidentifier Communication Port Management
Parallelport: Parallel Communication Port
Parallelportevent parallel port event
SerialPort RS-232 serial communication port
Serialportevent serial port event

Three exception classes
Nosuchportexception thrown when the driver cannot find the specified port
Portinuseexception thrown when a specified port is in use
The unsupportedcommoperationexception driver cannot throw

Instance
Another examples file downloaded along with the API contains six programs. 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;
Static enumeration portlist; // enumeration class

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 (comport) obtains the comportidentifier object corresponding to the port opened by the application. Getportidentifier (string portname) is used to obtain the commp ortidentifier object of the specified port name (such as "COM1. */

While (portlist. hasmoreelements ()){
Portid = (comatrix ortidentifier) portlist. nextelement ();
If (portid. getporttype () = comatrix ortidentifier. port_serial)/* The getporttype method returns the port type */{
// If (portid. getname (). Equals ("COM1")/* Find the first serial port in Windows */{
If (portid. getname (). Equals ("/dev/Term/a")/* Find the first serial port in Unix-like system */{
Simpleread reader = new simpleread ();
}
}
}
}

Public simpleread (){
Try {
SerialPort = (SerialPort) portid. Open ("simplereadapp", 2000);/* Open the communication port by using the open method to obtain a comport object. It excludes the program port. If the port is being occupied by another application, a port_ownership_requested event will be passed using the comatrix event mechanism. Each port is associated with an inputstream and an outputstream. If the port is opened using the open method, any getinputstream will return the same data stream object unless close is called. There are two parameters: the first parameter is the application name, and the second parameter is the number of milliseconds when the port is opened. */
} Catch (portinuseexception e ){}
Try {
Inputstream = SerialPort. getinputstream ();/* Get the input stream object of the port */
} Catch (ioexception e ){}
Try {
SerialPort. addeventlistener (this);/* register a serialporteventlistener event to listen for a serial event */
} Catch (toomanylistenersexception e ){}

SerialPort. yonyondataavailable (true);/* Data Available */

Try {
SerialPort. setserialportparams (9600,
SerialPort. databits_8,
SerialPort. stopbits_1,
SerialPort. parity_none);/* set the serial port initialization parameters, which are baud rate, data bit, stop bit, and verification */
} 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];

Try {
While (inputstream. Available ()> 0 ){
Int numbytes = inputstream. Read (readbuffer );
}
System. Out. Print (new string (readbuffer ));
} Catch (ioexception e ){}
Break;
}
}
}
(PS: This usage of thread is not recommended. For details, see core Java volumeii.)

Serial Port writing routine
Put the string "Hello, world! /N "writes to the first serial port of the system

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 that comatrix ortidentifier provides the Open Method to open the communication port, but there is no corresponding method to close the port. to close the port, we need to call close () of javax. Comm. comatrix class (). Comport is an advanced abstraction in this package. It defines various things that a port can do: getting an I/O Data Stream object, controlling the buffer size, and adjusting input processing.

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.