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()); }
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) {}
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();
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!

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.

Java's strong typed system ensures platform independence through type safety, unified type conversion and polymorphism. 1) Type safety performs type checking at compile time to avoid runtime errors; 2) Unified type conversion rules are consistent across all platforms; 3) Polymorphism and interface mechanisms make the code behave consistently on different platforms.

JNI will destroy Java's platform independence. 1) JNI requires local libraries for a specific platform, 2) local code needs to be compiled and linked on the target platform, 3) Different versions of the operating system or JVM may require different local library versions, 4) local code may introduce security vulnerabilities or cause program crashes.

Emerging technologies pose both threats and enhancements to Java's platform independence. 1) Cloud computing and containerization technologies such as Docker enhance Java's platform independence, but need to be optimized to adapt to different cloud environments. 2) WebAssembly compiles Java code through GraalVM, extending its platform independence, but it needs to compete with other languages for performance.

Different JVM implementations can provide platform independence, but their performance is slightly different. 1. OracleHotSpot and OpenJDKJVM perform similarly in platform independence, but OpenJDK may require additional configuration. 2. IBMJ9JVM performs optimization on specific operating systems. 3. GraalVM supports multiple languages and requires additional configuration. 4. AzulZingJVM requires specific platform adjustments.

Platform independence reduces development costs and shortens development time by running the same set of code on multiple operating systems. Specifically, it is manifested as: 1. Reduce development time, only one set of code is required; 2. Reduce maintenance costs and unify the testing process; 3. Quick iteration and team collaboration to simplify the deployment process.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor
