0

当我按下遥控器中的一个按钮时,我试图从伺服器获得连续(180 到 0 和返回 0 到 180)的运动,并且只有在我按下另一个按钮时才停止。到目前为止,我已经让它连续移动,但是当我按下“停止”按钮时它并没有停止。我知道这是因为 while 循环。但是,我已经尝试过 switch-case,if 语句,到目前为止没有任何效果。请帮助,任何使它工作的建议表示赞赏。

#include <Servo.h>

#define code1 2534850111 //decimal value of button 1
#define code3 16724175   //decimal value of button 1
#define code 4294967295   //random value
#define code2 16738455   //decimal value of button 0
#define code4 3238126971   //decimal value of button 0

Servo myservo; // servo object
int RECV_PIN = 11; //receiveing pin IR remote

int pos = 0;

IRrecv irrecv(RECV_PIN); 

decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();  //start the receiver
  myservo.attach(9);    //servo connect to pin 9
  pinMode(2, OUTPUT);   //LED connect to pin 2
}

void loop() {
  if(irrecv.decode(&results)){
     // if(results.value == code1 || results.value == code3){
     while(results.value == code1 || results.value == code3){
        digitalWrite(2,HIGH); //turn the led on
        for(pos = 0; pos <= 180; pos += 1){ //servo goes form 0 to 180             degrees in steps of 1 degree
    myservo.write(pos);
    delay(7);
    }
    for(pos = 180; pos >= 0; pos -= 1){ //servo goes back from 180 to 0 degrees with 1 degree step
    myservo.write(pos);
    delay(7);
}
    }

 while(results.value == code2 || results.value == code4){
       digitalWrite(2, LOW);  // turn the led off
       myservo.write(pos);
       delay(15);
       break;
 }

  Serial.println(results.value, DEC); //show the decimal value of the     pressed button
  irrecv.resume();  //receive the next value
    }

}
4

1 回答 1

0

解决问题的一种方法是检查内部是否存在“按钮按下” loop()。将您的按钮检查放在您的运动for循环中以立即捕捉更改。看起来您可能有两个起始码(?),因此您可能必须更改if下面的语句,但希望我在下面的代码示例中演示如何检查条件以“继续”。

void loop()
{
    if(irrecv.decode(&results))
    {
        // turn one way
        for(pos = 0; pos <= 180; pos += 1)
        {
            // only continue if the start code(s) still active
            if(results.value == STARTCODE || results.value == OTHERSTARTCODE)
            {
                myservo.write(pos);
                delay(7);
                irrecv.resume();  //receive the next value
            }
        }
        // turn the other way
        for(pos = 180; pos >= 0; pos -= 1)
        {
            // only continue if the start code(s) still active
            if(results.value == STARTCODE || results.value == OTHERSTARTCODE)
            {
                myservo.write(pos);
                delay(7);
                irrecv.resume();  //receive the next value
            }
        }
    }   
}
于 2017-06-22T15:22:24.533 回答