从Java发送字节时,Arduino崩溃

时间:2014-06-06 15:38:46

标签: java macos serial-port arduino rxtx

我使用arduino网站上的sample program来通过串口发送和接收数据到我的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();
}

我在上面尝试的是在调用方法时只发送一个字符。我只发了一个&#39; 0&#39;用于测试的字符。手动调用方法两到三次后,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();


}

正在读取串行接口的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.
}

1 个答案:

答案 0 :(得分:1)

您的Arduino代码通过串行连接发回数据,但您不是从Java程序中读取它。填充各种缓冲区并不需要很长时间,然后Arduino正在等待您解除阻塞。

您需要从串口读取输出并使用它做一些事情。我建议运行一个后台线程,阻止读取串口,只需将字符写入System.out并在收到时刷新。