我编写了一个使用Java程序控制Arduino over serial的系统。 Arduino从Java程序接收char
并基于char
执行基于预编程的操作。当我使用Arduino Programmer串行监视器发送字符时,Arduino完全按预期工作,但当我尝试从Java发送相同的字符时,Arduino没有响应。
这是Arduino代码:
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() == 1) {
char serialData = Serial.read();
// Activate servos based on input
switch (serialData) {
case '1':
activateServo();
break;
case '2':
readSensor1();
break;
case '3':
readSensor2();
break;
default:
// Ignore input
break;
}
}
}
void activateServo() {
// Code removed
}
void readSensor1() {
// Code removed
}
void readSensor2() {
// Code removed
}
这是Java代码。请注意,我使用jSerialComm API:
import java.io.PrintWriter;
import java.time.Duration;
import java.time.Instant;
import com.fazecast.jSerialComm.SerialPort;
public class SerialWriteTest {
private static char dataToSend = '1';
public static void main(String[] args) {
// Find all available ports
SerialPort[] computerPorts = SerialPort.getCommPorts();
// Select COM3
SerialPort selectedPort = null;
for (SerialPort p : computerPorts) {
if (p.getSystemPortName().equals("COM3")) {
selectedPort = p;
}
}
// Try to open port, terminate execution if not possible
if (selectedPort == null) {
return;
} else if (selectedPort.openPort()) {
System.out.println(selectedPort.getSystemPortName() + " successfully opened.");
} else {
System.out.println(selectedPort.getSystemPortName() + " failed to open.");
return;
}
// Set port to scanner mode
selectedPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
// Read from port and display
try (PrintWriter output = new PrintWriter(selectedPort.getOutputStream())) {
// Wait for 100 ms
Instant start = Instant.now();
while (Duration.between(start, Instant.now()).toMillis() < 100) {}
try {
output.write('1');
output.flush();
System.out.println("Sent");
} catch (Exception e) {
System.out.println("Failed to send");
}
}
selectedPort.closePort();
System.out.println("--- Main finished ---");
}
}
由于Arduino似乎正在使用串行监视器,我确定该程序在Java程序中。任何人都可以看到为什么Java程序似乎没有发送角色&#39; 1&#39;喜欢它应该?