最近了解到的需求是需要需激光打刻机进行(RS)串口通信这里使用的是RXTX开源包实现的
之前并没有用java做过串口通信而且这方面资料不是很多
项目实际应用中可能会采用VB开发(这个我就不会了)
只不过用java尝试一下记个笔记希望可以对相关开发用些帮助
下面是实现代码
Java代码
package test;
import javaioIOException;
import javaioInputStream;
import javaioInputStreamReader;
import javaioOutputStream;
import javautilDate;
import javautilEnumeration;
import javautilTooManyListenersException;
import gnuioCommPortIdentifier;
import gnuioPortInUseException;
import gnuioSerialPort;
import gnuioSerialPortEvent;
import gnuioSerialPortEventListener;
import gnuioUnsupportedCommOperationException;
public class CommUtil implements SerialPortEventListener {
InputStream inputStream; // 从串口来的输入流
OutputStream outputStream;// 向串口输出的流
SerialPort serialPort; // 串口的引用
CommPortIdentifier portId;
public CommUtil(Enumeration portList String name) {
while (portListhasMoreElements()) {
CommPortIdentifier temp = (CommPortIdentifier) portListnextElement();
if (tempgetPortType() == CommPortIdentifierPORT_SERIAL) {// 判断如果端口类型是串口
if (tempgetName()equals(name)) { // 判断如果端口已经启动就连接
portId = temp;
}
}
}
try {
serialPort = (SerialPort) portIdopen(My+name );
} catch (PortInUseException e) {
}
try {
inputStream = serialPortgetInputStream();
outputStream = serialPortgetOutputStream();
} catch (IOException e) {
}
try {
serialPortaddEventListener(this); // 给当前串口天加一个监听器
} catch (TooManyListenersException e) {
}
serialPortnotifyOnDataAvailable(true); // 当有数据时通知
try {
serialPortsetSerialPortParams( SerialPortDATABITS_ // 设置串口读写参数
SerialPortSTOPBITS_ SerialPortPARITY_NONE);
} catch (UnsupportedCommOperationException e) {
}
}
public void serialEvent(SerialPortEvent event) {
switch (eventgetEventType()) {
case SerialPortEventBI:
case SerialPortEventOE:
case SerialPortEventFE:
case SerialPortEventPE:
case SerialPortEventCD:
case SerialPortEventCTS:
case SerialPortEventDSR:
case SerialPortEventRI:
case SerialPortEventOUTPUT_BUFFER_EMPTY:
break;
case SerialPortEventDATA_AVAILABLE:// 当有可用数据时读取数据并且给串口返回数据
byte[] readBuffer = new byte[];
try {
while (inputStreamavailable() > ) {
Systemoutprintln(inputStreamavailable());
int numBytes = inputStreamread(readBuffer);
Systemoutprintln(numBytes);
}
Systemoutprintln(new String(readBuffer)trim());
} catch (IOException e) {
eprintStackTrace();
}
break;
}
}
public void send(String content){
try {
outputStreamwrite(contentgetBytes());
} catch (IOException e) {
eprintStackTrace();
}
}
public void ClosePort() {
if (serialPort != null) {
serialPortclose();
}
}
}
测试
Java代码
package test;
import gnuioCommPortIdentifier;
import javautilEnumeration;
public class Test {
public static void main(String[] args) throws InterruptedException {
Enumeration portList = CommPortIdentifiergetPortIdentifiers(); //得到当前连接上的端口
CommUtil comm = new CommUtil(portListCOM);
int i = ;
while(i<)
{
Threadsleep();
commsend(hello);
i++;
}
commClosePort();
}
}