import com.fazecast.jSerialComm.SerialPort;
import java.nio.charset.StandardCharsets;
public class SendAndReceiveFromAllPorts {
public static void main(String[] args) {
SerialPort[] ports = SerialPort.getCommPorts();
// 统一的发送指令(16 进制)
byte[] sendCommand = new byte[]{0xAA, 0xBB, 0xCC};
for (SerialPort port : ports) {
port.openPort();
port.setBaudRate(9600);
// 发送指令
port.writeBytes(sendCommand, sendCommand.length);
// 接收响应
byte[] receiveBuffer = new byte[1024];
int numRead = port.readBytes(receiveBuffer, receiveBuffer.length);
if (numRead > 0) {
String receivedData = new String(receiveBuffer, 0, numRead, StandardCharsets.UTF_8);
System.out.println("从端口 " + port.getSystemPortName() + " 接收到的数据: " + receivedData);
}
port.closePort();
}
}
}