从Arduino发送数据到Android无法正常工作

时间:2018-05-27 21:46:49

标签: android bluetooth arduino

我们正在开展一个项目,我们使用Arduino和蓝牙HC-06移动伺服电机来打开和关闭锁。我们尝试在执行任何操作之前发送一个数字(1或2)作为伺服电机的状态,只要我们将应用程序连接到蓝牙HC-06,就知道锁已经打开或关闭(我们是使用EEPROM不丢失伺服的最后位置)。但是,使用我们的代码,我们会收到数据,但伺服停止运行良好。如果我们从循环中删除前两行,它将起作用,但我们不知道伺服的初始状态。我们怎样解决这个问题?

char state;
Servo myservo;

int btx=3;
int brx=2;

SoftwareSerial blue(btx,brx);

int pos = 0;

void setup() {

  Serial.begin(9600);    
  myservo.attach(9);
  blue.begin(9600);

  // An EEPROM value of 1 == UNLOCKED and a value of 2 == LOCKED
  if(EEPROM.read(0) == 1){ //Lock opened         
    myservo.write(70);
    delay(200);
    pos = 1;
    //blue.println(1); not working
  }
  else if(EEPROM.read(0) == 2){ //Lock closed 
    myservo.write(180);
    delay(200);
    pos = 2;
    //blue.println(2); not working
  }
  //blue.println(pos); not working
}

void loop() {
  while(!blue.available()){ // <-- The problem is in this two lines
      blue.println(pos); // send state to app
  }
  String voice;
  while(blue.available()){
    delay(10);                 
    char c = blue.read();   
    if (c == '#'){
      break;                   
    }
    voice += c;               
  }

  if(voice.length() > 0){
    if (voice == "open"){ 
      myservo.write(70);
      EEPROM.write(0, 1);
      blue.println(1);
      delay(15);
    }
    else if (voice == "close"){
      myservo.write(180); 
      EEPROM.write(0, 2);
      blue.println(2);
      delay(15);
  }
}  
}

1 个答案:

答案 0 :(得分:0)

因为这两行是无限循环!因此,您应该将代码更改为此代码并让代码有机会继续:)

void loop() {
        if(!blue.available()){
            blue.println(pos);
        }else if(blue.available()){
            String voice;

            while(blue.available()){
                delay(10);
                char c = blue.read();
                if (c == '#'){
                    break;
                }
                voice += c;

                if(voice.length() > 0){
                    if (voice == "open"){
                        myservo.write(70);
                        EEPROM.write(0, 1);
                        blue.println(1);
                        delay(15);
                    }
                    else if (voice == "close"){
                        myservo.write(180);
                        EEPROM.write(0, 2);
                        blue.println(2);
                        delay(15);
                    }
                }
            }
        }
    }