我要简短而简单 . 我有一个arduino,它通过串行通信将数据发送到java脚本 . 在加电和休息时,arduino将不可见数据发送到需要清除/清除的串口 . 我尝试从arduino和java程序进行串行刷新,似乎都没有工作 . 我的arduino代码和java代码发布在下面 . 提前致谢!
void setup() {
delay(2500);
Serial.begin(9600);
flushreceive();
pinMode(13, OUTPUT);
}
void loop() {
char input;
if (Serial.available()) {
input = Serial.read();
//Turn on the LED.
if(input == '1'){
digitalWrite(13, HIGH);
Serial.print("ON");
flushreceive();
}
//Have the LED blink 10 times.
if(input == '2') {
Serial.print("OX");
for(int i = 0; i < 10; i++) {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(100);
flushreceive();
}
}
//Turn off the LED.
if(input == '3') {
digitalWrite(13, LOW);
Serial.print("OFF");
flushreceive();
}
} // END IF SERIAL AVAILABLE
} // END LOOP
void flushreceive() {
while(Serial.available())
Serial.flush();
}
下面是我的java代码,当按下按钮时,它会将代码发送到arduino,它打开或关闭LED,arduino发回OFF或ON的确认但是我没有收到这个... ...角色进来或根本没有 .
//Listener for the blink button.
btnBlink.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnOn.setBackground(null);
btnBlink.setBackground(Color.yellow);
btnOff.setBackground(null);
//Turns on the #13 pin LED and flashes it 10 times.
if(comPort.isOpen() == true) {
InputStream inPut = comPort.getInputStream();
BufferedReader readBuffer = new BufferedReader(new InputStreamReader(inPut));
//Send a 2 to the Arduino and update the user.
lblStatus.setText("Status: LED Blinking");
outPut.print("2");
outPut.flush();
byte[] buffer = new byte[2];
try {
String message = "OX";
int len = inPut.read(buffer);
if (len > 0) {
message = new String(buffer);
System.out.println(message);
}
if (message.trim().contains("OX")) {
btnBlink.setBackground(Color.yellow);
outPut.flush();
} else {
System.out.println("ERROR!!"));
}
} catch (Exception ep) { ep.printStackTrace(); }
} else {
//Update the status/console if the Arduino hasn't been connected.
lblStatus.setText("Status: Connect Arduino");
}
}
});
1 回答
我使用Arduino Playground和
rxtx
库中的代码从arduino serial获取数据到我的java程序,它像魔术一样工作 .这两个链接都在这里:
https://playground.arduino.cc/Interfacing/Java
http://rxtx.qbang.org/wiki/index.php/Download
您只需要设置正确的端口号和波特率(因为波特率通常是:
9600
和com端口因设备而异,因为我的情况是COM3
)