我使用了sample program从 arduino 网站,以便通过串口向我的 Arduino 发送和接收数据。然而,由于某种原因,即使我尝试只发送一个字节,Arduino 也会在一段时间后崩溃。如果我通过 IDE 自己的串行监视器手动发送字符,则不会发生这种情况。
我编写了以下方法将字符输出到Arduino:
public synchronized void serialWrite(char sendIt){
try {
output.write((byte)'0');
output.flush();
for (int j=0;j<1000000000;j++){
}
}catch (Exception e){System.out.println("Not connected...");}
notify();
}
我上面尝试的是在调用该方法时仅发送一个字符。我只发送一个“0”字符进行测试。手动调用该方法两三次后,Arduino 崩溃。 有什么我应该调查的吗?
Arduino 代码:
#include <SoftwareSerial.h>
int buttonState=0;
int lastButtonState=0;
int buttonPushCounter=0;
long previousMillis=0;
long interval=250;
int ledState=LOW;
int ledState2=LOW;
int ledState3=LOW;
long timeElapsed=0;
SoftwareSerial portOne(10,11);
void setup(){
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(2,INPUT);
Serial.begin(9600);
portOne.begin(9600);
}
boolean turnoff;
void loop(){
if(portOne.overflow()){
Serial.println("There's an overflow here!");
}
buttonState= digitalRead(2);
if(buttonState!=lastButtonState){
if (buttonState==HIGH){
buttonPushCounter++;
}
}
lastButtonState=buttonState;
if (turnoff){
unsigned long currentMillis=millis();
if (currentMillis-previousMillis>0 && currentMillis-previousMillis<interval){
ledState=HIGH;
ledState2=LOW;
ledState3=LOW;
}else
if (currentMillis-previousMillis>interval && currentMillis-previousMillis<interval*2){
ledState=LOW;
ledState2=LOW;
ledState3=HIGH;
}else
if (currentMillis-previousMillis>interval*2 && currentMillis-previousMillis<interval*3){
ledState=LOW;
ledState2=HIGH;
ledState3=LOW;
}else if (currentMillis-previousMillis>interval*3){
previousMillis=currentMillis;
}
digitalWrite(3,ledState);
digitalWrite(4,ledState2);
digitalWrite(5,ledState3);
}else{
digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5,LOW);
}
if (buttonPushCounter==1){
Serial.print("Button pressed!\n");
turnoff=!turnoff;
buttonPushCounter=0;
}
noInterrupts();
char ch=Serial.read();
delay(1);
if(ch=='0'){
Serial.println("Changed by serial"+turnoff);
Serial.println(ch);
turnoff=!turnoff;
}
interrupts();
}
读取串行接口(interface)的java程序部分是这样的:
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=input.readLine();
System.out.println(inputLine);
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
最佳答案
您的 Arduino 代码正在通过串行连接发送回数据,但您没有从 Java 程序中读取数据。不需要很长时间,各种缓冲区就会填满,然后 Arduino 就会等待您解锁它们。
您需要读取串行端口的输出并对其执行某些操作。我建议运行一个后台线程,该线程会阻止读取串行端口,并将字符写入 System.out,并在收到字符时刷新。
关于java - 从 Java 发送字节时 Arduino 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085730/