직렬 데이터를 사용하여 Java 프로그램을 작성 중입니다. 내 arduino가 연결이 끊어지는 문제를 해결할 수있는 방법에 궁금합니다. 따라서 직렬 데이터를 중지 한 다음 다시 연결하여 인간과의 상호 작용없이 데이터를 다시 전송하기 시작합니다.사용자 상호 작용없이 Java에서 직렬 포트를 다시 연결하십시오.
public void initialize() {
working = 1;
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
thirdDC = "Could not find COM Port. Error";
System.out.println(thirdDC);
return;
}
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
System.out.println("WORKING");
} catch (Exception e) {
System.err.println(e.toString() + "NOPE");
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
public synchronized void serialEvent(SerialPortEvent oEvent) {
String stop = "ERROR";
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
serialI = true;
try {
inputLine=input.readLine();
if (inputLine.equals(y)){
System.out.println(y);
temp1 = "OFF";
value = 0;
}
if (inputLine.equals(z)){
System.out.println(z);
temp1 = "ON";
value = 0;
}
if (inputLine.equals(stop)){
System.out.println(stop);
temp = "ERROR";
value = 1;
}
x = Double.parseDouble(inputLine);
if (x > 0){
temp = inputLine;
System.out.println(x);
value = 0;
}
} catch (Exception e) {
}
}else{
}
}
위의 코드는 내가 편집해야하는 방법입니다. 그래서 제 질문은 USB 코드를 뽑을 때 동시에 어떻게 직렬 포트를 닫을 수 있습니까? 그런 다음 USB 코드를 다시 꽂으면 프로그램이 어떻게 다시 꽂혀 있고 직렬로 통신하고 있다는 것을 인식 할 수 있습니까?
그럼 뭐가 문제입니까? 재 시도가있는 루프를 작성하는 방법은 무엇입니까? – EJP
@EJP, 나는 다시 포스트를 편집했다. 하지만 예, 내 질문의 첫 번째 부분은 USB가 뽑히는 경우 프로그램의 사용자에게 알려주는 메시지를 작성하는 방법입니다. 다시 연결되면 메시지가 사라지고 아무 일도 일어나지 않는 것처럼 프로그램이 계속됩니다. – Patrick