Home > Java > javaTutorial > A brief introduction to Java's serial communication

A brief introduction to Java's serial communication

高洛峰
Release: 2016-12-19 17:02:56
Original
1908 people have browsed it

Introduction to Java serial communication, many applications and tests of embedded systems or sensor networks require communication with embedded devices or sensor nodes through a PC. Among them, the most commonly used interfaces are RS-232 serial port and parallel port (in view of the complexity of the USB interface and the fact that it does not require a large amount of data transmission, the USB interface is still too extravagant to use here. Moreover, in addition to SUN, there is currently a package that supports USB. I haven't seen any other Java libraries that support USB directly).

SUN's CommAPI provides support for commonly used RS232 serial port and IEEE1284 parallel port communications respectively. RS-232-C (also known as EIA RS-232-C, hereinafter referred to as RS232) was developed in 1970 by the Electronic Industries Association (EIA) in conjunction with Bell Systems, modem manufacturers and computer terminal manufacturers for serial communications. standards. RS232 is a full-duplex communication protocol that can receive and send data at the same time.

1 Common Java serial port packages

Currently, common Java serial port packages include the serial communication API released by SUN in 1998: comm2.0.jar (under Windows), comm3.0.jar (Linux/Solaris); IBM Serial communication API and an open source implementation. Since SUN's API is commonly used under Windows and IBM's implementation is the same as SUN's at the API level, the open source implementation is not as reassuring as the products of the two major manufacturers. Here we only introduce SUN's serial port communication. API usage under Windows platform.

According to its instructions (Readme.html), if you want to use the serial port package for serial communication, in addition to setting the environment variables, you must also copy win32com.dll to the bin directory; copy comm.jar to lib ;Copy javax.comm.properties to the lib directory as well. However, when actually running and using the serial port package, just doing these is not enough.

Because usually when running "java MyApp", MyApp is started by the virtual machine under JRE. We only copy the above files to the corresponding directory of JDK, so the application will prompt that the serial port cannot be found. The solution to this problem is very simple. We only need to put the files mentioned above in the corresponding directory of the JRE.

It is worth noting that when using the serial port API in network applications, you will encounter other more complex problems. If you are interested, you can check out the post "About the problem of Applet using javacomm20 to read the client serial port on the web page" in the CSDN community.

2 Overview of Serial Port API

2.1 javax.comm.CommPort

This is an abstract class used to describe a port supported by the underlying system. It contains some high-level IO control methods that are common to all different communication ports. SerialPort and ParallelPort are both its subclasses. The former is used to control the serial port and the latter is used to control the parallel port. Both have different control methods for their underlying physical ports. Here we only care about SerialPort.

2.2 javax.comm.CommPortIdentifier

This class is mainly used to manage and set up the serial port. It is the core class for access control of the serial port. It mainly includes the following methods

Determine whether there is an available communication port

Open the communication port for IO operations

Determine the ownership of the port

Handle contention for port ownership

Manage events caused by changes in port ownership

2.3 javax.comm.SerialPort

This class is used to describe the underlying interface of an RS-232 serial communication port. It defines the minimum set of functions required for serial communication. Through it, users can directly read, write and set up the serial port.

2.4 Serial Port API Example

A long paragraph of text cannot be as clear as a small example. Let’s take a look at the example that comes with the serial port package---a small piece of code in SerialDemo to deepen the understanding of the serial port API core class. knowledge of how to use it.

2.4.1 List all available serial ports on this machine

void listPortChoices() {  
CommPortIdentifier portId;  
Enumeration en = CommPortIdentifier.getPortIdentifiers();  
// iterate through the ports.  
while (en.hasMoreElements()) {  
portId = (CommPortIdentifier) en.nextElement();  
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {  
System.out.println(portId.getName());  
}  
}  
portChoice.select(parameters.getPortName());  
}
Copy after login

The above code can list all available serial port names in the current system. The output results on my machine are COM1 and COM3.

2.4.2 Configuration of serial port parameters

Serial ports generally have the following parameters that can be configured before opening the serial port: including baud rate, input/output flow control, number of data bits, stop bits and parity.

SerialPort sPort;  
try {  
sPort.setSerialPortParams(BaudRate,Databits,Stopbits,Parity);  
//设置输入/输出控制流  
sPort.setFlowControlMode(FlowControlIn | FlowControlOut);  
} catch (UnsupportedCommOperationException e) {}
Copy after login

2.4.3 Serial port reading and writing

You need to open a serial port before reading and writing to the serial port:

CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(PortName);  
try {  
SerialPort sPort = (SerialPort) portId.open("串口所有者名称", 超时等待时间);  
} catch (PortInUseException e) {//如果端口被占用就抛出这个异常  
throw new SerialConnectionException(e.getMessage());  
}  
//用于对串口写数据  
OutputStream os = new BufferedOutputStream(sPort.getOutputStream());  
os.write(int data);  
//用于从串口读数据  
InputStream is = new BufferedInputStream(sPort.getInputStream());  
int receivedData = is.read();
Copy after login

The read out is int type, you can convert it into other types as needed.

It should be noted here that since the Java language does not have unsigned types, that is, all types are signed, you should pay special attention when converting from byte to int. Because if the highest bit of byte is 1, 1 will be used as a placeholder when converted to int type. In this way, the original byte type number of 10000000 becomes int type and becomes 1111111110000000. This is a very serious problem and should be avoided.

3 Common modes and problems of serial port communication

Finally finished talking about the basic knowledge that I hate most, let’s start our focus this time-the research of serial port applications. Since writing data to the serial port is very simple, here we only focus on reading data from the serial port.

Usually, there are two modes for serial communication applications. One is to implement the SerialPortEventListener interface to monitor various serial port events and handle them accordingly; the other is to establish an independent receiving thread specifically responsible for receiving data. Since these two methods have serious problems in some cases (as for the problem, I will leave it open for now), so my implementation is to use the third method to solve this problem.


For more articles related to simple introduction to Java’s serial communication, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template