SpringBoot接入RS-232串口通讯实现数据交互
在Spring Boot中接入RS-232串口通讯,可以使用Java的通信API,如javax.comm
或开源库jSerialComm
。以下是使用jSerialComm
的一个简单示例:
- 首先,添加
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) throws SerialPortException {
SerialPort[] commPorts = SerialPort.getCommPorts();
for (SerialPort port : commPorts) {
if (port.getSystemPortName().equals(portName)) {
serialPort = port;
serialPort.setBaudRate(baudRate);
serialPort.openPort();
break;
}
}
}
public void writeToPort(String message) throws SerialPortException {
if (serialPort != null && serialPort.isOpen()) {
serialPort.write(message.getBytes(), 0);
}
}
public String readFromPort(int length) throws SerialPortException {
if (serialPort != null && serialPort.isOpen()) {
byte[] buffer = new byte[length];
int bytesRead = serialPort.readBytes(buffer, length);
return new String(buffer, 0, bytesRead);
}
return null;
}
public void closePort() throws SerialPortException {
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 demo(SerialPortService serialPortService) {
return (args) -> {
try {
serialPortService.openPort("COM3", 9600); // 选择正确的串口名称和波特率
serialPortService.writeToPort("Hello Serial Port\n");
Thread.sleep(1000); // 等待回复
String response = serialPortService.readFromPort(24);
System.out.println("Response: " + response);
serialPortService.closePort();
} catch (Exception e) {
e.printStackTrace();
}
};
}
}
确保选择正确
评论已关闭