add 串口工具测试
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
package org.nl;
|
||||
|
||||
import com.fazecast.jSerialComm.SerialPort;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/**
|
||||
@@ -9,5 +10,36 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
public class ApplicationTest {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 列出所有可用的串口
|
||||
SerialPort[] commPorts = SerialPort.getCommPorts();
|
||||
for (SerialPort port : commPorts) {
|
||||
System.out.println(port.getSystemPortName());
|
||||
}
|
||||
for (SerialPort serialPort : commPorts) {
|
||||
boolean com5 = serialPort.getSystemPortName().equals("COM5");
|
||||
if (com5){
|
||||
try {
|
||||
serialPort.openPort();// 打开串口
|
||||
serialPort.setComPortParameters(9600, 8, 1, 0);// 设置串口参数
|
||||
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);
|
||||
byte[] buffer = new byte[1024];
|
||||
while (true){
|
||||
Thread.sleep(300);
|
||||
int bytesRead = serialPort.readBytes(buffer, buffer.length);
|
||||
if (bytesRead > 0) {
|
||||
String input = new String(buffer, 0, bytesRead);
|
||||
System.out.println(input);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (serialPort.isOpen()) {
|
||||
serialPort.closePort();// 关闭串口
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user