java串口通讯demo
时间: 2023-09-12 21:07:41 浏览: 157
以下是一个简单的Java串口通信Demo:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
public class SerialComm implements SerialPortEventListener {
private SerialPort serialPort;
private InputStream inputStream;
private OutputStream outputStream;
private static final int BAUD_RATE = 9600;
private static final int DATA_BITS = 8;
private static final int STOP_BITS = 1;
private static final int PARITY = SerialPort.PARITY_NONE;
public static void main(String[] args) {
SerialComm serialComm = new SerialComm();
serialComm.searchForPorts();
serialComm.connect();
}
public void searchForPorts() {
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
CommPortIdentifier port = (CommPortIdentifier) portList.nextElement();
if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println(port.getName());
}
}
}
public void connect() {
CommPortIdentifier portIdentifier;
try {
portIdentifier = CommPortIdentifier.getPortIdentifier("COM3");
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Port is currently in use");
} else {
serialPort = (SerialPort) portIdentifier.open(this.getClass().getName(), 2000);
serialPort.setSerialPortParams(BAUD_RATE, DATA_BITS, STOP_BITS, PARITY);
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
System.out.println("Connected to port: " + portIdentifier.getName());
}
} catch (PortInUseException | UnsupportedCommOperationException | IOException | gnu.io.NoSuchPortException e) {
System.out.println(e.toString());
}
}
public void disconnect() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
@Override
public void serialEvent(SerialPortEvent spe) {
if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int availableBytes = inputStream.available();
byte[] bytes = new byte[availableBytes];
inputStream.read(bytes, 0, availableBytes);
System.out.println(new String(bytes));
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
}
```
这个Demo演示了如何搜索计算机上可用的串口,连接到指定的串口,读取串口数据并在控制台上显示。你可以根据自己的需求对代码进行修改。
阅读全文