In the past, I often used C language to operate the serial port to implement some small functions such as sending and receiving. Recently, serial port communication was also used in the project, but the language became Java, which is a little tricky.
Java is referenced by various libraries, so google searches for some requirements first ~~ For example, if I had read the webpage content for half a day before, I was thinking about it and writing it. It was charset, proxy, browsertype, dizzy, and finally took Jsoup for a while ...... However, before using it, you must fully consider the scalability and the richness of the API. Otherwise, the program will become more and more integrated. Let's talk about the serial port ......
Overview
Java commonly used (I used) serial port tools include javacomm and RXTX. The former only supports win32, and the latter supports both 32-bit and 64-bit versions. The usage is similar, so let's put it together:
After downloading the package, you will see a prompt such as readme. Copy the corresponding dll files and jar files to the/bin and/lib directories respectively, and view readme again when there is a problem. Run the attached routine.
The specific use process is: configure the port baud rate, parity bit and other information; open the serial port; write data; read output; close. This series of steps must not be reversed when writing programs.
Serial port configuration
You need to configure four items:
Baud rate (baudrate)-generally 9600, 115200
(Data bit) dataBits-generally 8 bits
DATABITS_5: 5 bits
DATABITS_6: 6 bits
DATABITS_7: 7 bits
DATABITS_8: 8 bits
(Stop bit) stopBits-generally 1 stop bit
STOPBITS_1: 1 stop bit
STOPBITS_2: 2 stop bits
Stopbits_00005: 1.5 stop bits
(Check bit) parity-if the check bit is not required, select SerialPort. PARITY_NONE
PARITY_NONE: no parity
PARITY_ODD: odd parity
PARITY_EVEN: even parity
PARITY_MARK: mark parity
PARITY_SPACE: space parity
FlowControlMode-General FLOWCONTROL_NONE
FLOWCONTROL_NONE: no flow control
FLOWCONTROL_RTSCTS_IN: RTS/CTS (hardware) flow control for input
FLOWCONTROL_RTSCTS_OUT: RTS/CTS (hardware) flow control for output
FLOWCONTROL_XONXOFF_IN: XON/XOFF (software) flow control for input
FLOWCONTROL_XONXOFF_OUT: XON/XOFF (software) flow control for output
Event listening
AddEventListener (SerialPortEventListener lsnr)
It is used to listen to serial events. The following events can be monitored:
BI (Break interrupt)
CD (Carrier detect)
CTS (Clear to send)
DATA_AVAILABLE (Data available at the serial port)
DSR (Data set ready)
EventType (Deprecated. Replaced by getEventType method)
FE (Framing error)
OE (Overrun error)
OUTPUT_BUFFER_EMPTY (Output buffer is empty)
PE (Parity error)
RI (Ring indicator)
Read Data
Use SerialPortEventListener to read DATA_AVAILABLE, save and process the serial content.
Write Data
GetOutputStream is the only method for sending data to the serial port. In use, write a byte string to OutPutStream, and then use SerialPortEventListener to obtain the feedback result.
RXTX routine (from here ):
Public class USBComm implements SerialPortEventListener {
Public static final String MESSAGE = "message to be send ";
/**
* Stream for the storage of incoming data
*/
Private InputStream inputStream;
/**
* Stream for the dispatching of data
*/
Private OutputStream outputStream;
/**
* Timeout of the USB port
*/
Private final int PORT_TIMEOUT = 2000;
/**
* Representation of the serial port used for the communication
*/
Public SerialPort serialPort;
/**
* Buffer that stores the stored Ed bytes from the media
*/
Protected define blockingqueue <Byte> receivedBytes;
/**
* Builds a new manager for the communication via USB port.
* @ Exception IOException if an error occurred during the opening of the USB port
*/
Public USBComm (String comm) throws IOException {
ReceivedBytes = new LinkedBlockingQueue <Byte> (100000 );
String port = comm; // place the right COM port here, OS dependent
// Check that the USB port exists and is recognized:
Enumeration <?> PortList = commp ortidentifier. getPortIdentifiers ();
Boolean portFound = false;
Commp ortidentifier portId = null;
While (portList. hasMoreElements ()){
PortId = (comatrix ortidentifier) portList. nextElement ();
If (portId. getPortType () = comatrix ortidentifier. PORT_SERIAL ){
If (portId. getName (). equals (port )){
Log. logAndDisplay (LogLevel. INFO, "SerialConnection", "Found port:" + port );
PortFound = true;
Break;
}
}
}
If (! PortFound)
Throw new IOException ("port" + port + "not found .");
Try {
Log. logAndDisplay (LogLevel. INFO, "SerialConnection", "USB port" + port + "opening ...");
SerialPort = (SerialPort) portId. open ("USBCommunicator", PORT_TIMEOUT );
InputStream = serialPort. getInputStream ();
OutputStream = serialPort. getOutputStream ();
SerialPort. addEventListener (this );
SerialPort. Yonyondataavailable (true );
Thread. sleep (1000 );
SerialPort. setSerialPortParams (serialPort. getBaudRate (),
SerialPort. getDataBits (),
SerialPort. getStopBits (),
SerialPort. getParity ());
SerialPort. setFlowControlMode (serialPort. getFlowControlMode ());
} Catch (Exception e ){
System. err. println (e. getMessage ());
Throw new IOException (e. getMessage ());
}
}
Public void closeUSB (){
// Close the streams for serial port:
Try {
InputStream. close ();
OutputStream. close ();
} Catch (IOException e ){
System. err. println ("Cannot close streams:" + e. getMessage ());
}
}
/**
* Listener for USB events
*
* @ Param event new event occurred on the USB port
*/
Public void serialEvent (SerialPortEvent event ){
Switch (event. getEventType ()){
Case SerialPortEvent. BI:
Case SerialPortEvent. OE:
Case SerialPortEvent. FE:
Case SerialPortEvent. PE:
Case SerialPortEvent. CD:
Case SerialPortEvent. CTS:
Case SerialPortEvent. DSR:
Case SerialPortEvent. RI:
Case SerialPortEvent. OUTPUT_BUFFER_EMPTY:
// Nothing to do...
Break;
Case SerialPortEvent. DATA_AVAILABLE:
Byte bytes ed =-1;
Do {
Try {
Received = (byte) inputStream. read ();
} Catch (IOException e ){
System. err. println ("Error reading USB:" + e. getMessage ());
}
Synchronized (receivedBytes ){
Try {
ReceivedBytes. add (received );
} Catch (IllegalStateException ew ){
System. err. println (ew. getMessage ());
ReceivedBytes. poll ();
ReceivedBytes. add (received );
}
}
} While (already ed! =-1 );
Break;
}
}
Public void write (byte [] buffer ){
Try {
OutputStream. write (buffer );
// OutputStream. flush ();
} Catch (IOException e ){
System. err. println ("Cannot write:" + e. getMessage ());
}
}
Public static void main (String [] args ){
USBComm usb;
Try {
Usb = new USBComm ("COM73"); // change to your port
Byte [] B = MESSAGE. getBytes ();
Usb. write (B );
Usb. serialPort. close ();
Usb. closeUSB ();
} Catch (IOException e ){
System. err. println ("IOException:" + e. getMessage ());
}
}
}