Arduino伺服和红外遥控器

问题描述:

我试图从遥控器中获得连续(180到0和从0到180)的移动,当我按下遥控器上的按钮时,只有当我按下另一个按钮时才停止。到目前为止,我已经让它不断移动,但是当我按下“停止”按钮时它不会停止。我知道这是因为while循环。但是,我已经尝试过使用switch-case,如果声明,迄今为止没有任何工作。 请帮助,任何建议,使其工作表示赞赏。Arduino伺服和红外遥控器

#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 
    } 

} 
+1

请编辑您的问题,并告诉我们您目前拥有的代码。如果没有(通常是接线图),我们真的没办法帮助你。 – stevieb

+0

我的水晶球并没有告诉我任何有关你的代码的东西:(:()( –

+0

)对不起,刚刚学习这个领域。我认为有一种更好的方法来附加除了每行4个空格以外的代码。这个问题,我希望你现在可以帮我:) – theagleye

解决您的问题的一种方法是检查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 
      } 
     } 
    } 
} 
+0

谢谢。你的代码看起来比我的好,但是并不完全符合我的要求;伺服仍然不会继续从0滚动到180并返回并继续执行,直到按下“结束代码”。它每次按下按钮180时都会移动到0以及0到180(这是代码告诉它正确的)。我不确定我是否已经明确提出了这个问题,但我希望是,如果我能以某种方式更清楚地告诉我,请告诉我。另外,是的,我有两个开始代码和两个终端代码。 – theagleye