Spring boot 使用 jSerialComm 对串口使用发送信息并接收
在Spring Boot中使用jSerialComm库进行串口通信,首先需要添加jSerialComm的依赖到项目中。以下是一个简单的例子,展示了如何在Spring Boot应用程序中发送和接收串口数据。
- 添加jSerialComm依赖到
pom.xml
:
<dependency>
<groupId>com.fazecast</groupId>
<artifactId>jSerialComm</artifactId>
<version>2.9.0</version>
</dependency>
- 创建一个服务来管理串口通信:
import com.fazecast.jSerialComm.SerialPort;
@Service
public class SerialPortService {
private SerialPort serialPort;
public void openPort(String portName, int baudRate) {
SerialPort[] commPorts = SerialPort.getCommPorts();
for (SerialPort port : commPorts) {
if (port.getSystemPortName().equals(portName)) {
serialPort = port;
serialPort.setComPortParameters(baudRate, 8, 1, 0);
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
serialPort.openPort();
break;
}
}
}
public void sendData(String data) {
if (serialPort != null && serialPort.isOpen()) {
serialPort.writeBytes(data.getBytes(), data.getBytes().length);
}
}
public String receiveData() {
if (serialPort != null && serialPort.isOpen()) {
byte[] buffer = new byte[1024];
int bytesRead = serialPort.readBytes(buffer, buffer.length);
if (bytesRead > 0) {
return new String(buffer, 0, bytesRead);
}
}
return "";
}
public void closePort() {
if (serialPort != null && serialPort.isOpen()) {
serialPort.closePort();
}
}
}
- 在Spring Boot应用程序中使用这个服务:
@SpringBootApplication
public class SerialCommApplication {
public static void main(String[] args) {
SpringApplication.run(SerialCommApplication.class, args);
}
@Bean
public CommandLineRunner serialPortRunner(SerialPortService serialPortService) {
return args -> {
// 打开串口
serialPortService.openPort("COM3", 9600);
// 发送数据
serialPortService.sendData("Hello Serial Port\n");
// 接收数据
String receivedData = serialPortService.receiveData();
System.out.println("Received Data: " + receivedData);
// 关闭串口
评论已关闭