import com.fazecast.jSerialComm.SerialPort;
public class ListTTLPort {
public static void main(String[] args) {
SerialPort[] ports = SerialPort.getCommPorts();
for (SerialPort port : ports) {
System.out.println("Port Name: " + port.getSystemPortName());
System.out.println("Port Description: " + port.getPortDescription());
System.out.println("----------------------");
}
}
}
import com.fazecast.jSerialComm.SerialPort;
import java.nio.charset.StandardCharsets;
public class TwoTTLControl {
public static void main(String[] args) {
// 找到第一个 TTL 设备
SerialPort port1 = findPort("Port1Description");
if (port1 == null) {
System.out.println("未找到第一个指定的串口");
return;
}
port1.openPort();
port1.setBaudRate(9600);
// 找到第二个 TTL 设备
SerialPort port2 = findPort("Port2Description");
if (port2 == null) {
System.out.println("未找到第二个指定的串口");
port1.closePort();
return;
}
port2.openPort();
port2.setBaudRate(9600);
// 发送数据到第一个 TTL 设备
String dataToSend1 = "Data for TTL 1";
byte[] dataBytes1 = dataToSend1.getBytes(StandardCharsets.UTF_8);
port1.writeBytes(dataBytes1, dataBytes1.length);
// 发送数据到第二个 TTL 设备
String dataToSend2 = "Data for TTL 2";
byte[] dataBytes2 = dataToSend2.getBytes(StandardCharsets.UTF_8);
port2.writeBytes(dataBytes2, dataBytes2.length);
// 接收数据(示例中仅接收第一个 TTL 设备的数据)
byte[] readBuffer1 = new byte[1024];
int numRead1 = port1.readBytes(readBuffer1, readBuffer1.length);
if (numRead1 > 0) {
String receivedData1 = new String(readBuffer1, 0, numRead1, StandardCharsets.UTF_8);
System.out.println("从第一个 TTL 设备接收到的数据: " + receivedData1);
}
port1.closePort();
port2.closePort();
}
public static SerialPort findPort(String portDescription) {
SerialPort[] ports = SerialPort.getCommPorts();
SerialPort port = null;
for (SerialPort p : ports) {
if (p.getPortDescription().contains(portDescription)) {
port = p;
break;
}
}
return port;
}
}