Search code examples
arduinoarduino-unoarduino-ide

Servo rotating infinitely when I want it to do so only once


I am very new to Arduino. I want to make a simple setup, in which, pressing a button on a remote will make the servo rotate 90 degree and come back to 0.

Here is my code:

#include <Servo.h>
#include <IRremote.h>
int receiver = 13;
IRrecv irrecv(receiver);
decode_results results;
Servo myServo;
int pos = 0;
void setup() {
  // put your setup code here, to run once:
  myServo.attach(9);
  Serial.begin(9600);
  irrecv.enableIRIn();
  myServo.write(0);
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results)){
    
  
    if (results.value== 0xC0000C){
      for (pos = 0; pos <= 90; pos += 1) { 
        // in steps of 1 degree
        myServo.write(pos);              
        delay(15);                       
      }
      for (pos = 90; pos >= 0; pos -= 1) { 
        myServo.write(pos);              
        delay(15);                       
      }
    }
  }
  delay(100);
}

However, when I press the button assigned, the servo keeps swinging from 0 to 90 degree and back infinitely, but I only want it to do so once, each time the button is pressed. How do I do that?


Solution

  • You need to add the line

    irrecv.resume();
    

    to the end if loop just before that final delay in order to clear out the results and start looking for a new signal.

    void loop() {
      // put your main code here, to run repeatedly:
      if (irrecv.decode(&results)){
        
      
        if (results.value== 0xC0000C){
          for (pos = 0; pos <= 90; pos += 1) { 
            // in steps of 1 degree
            myServo.write(pos);              
            delay(15);                       
          }
          for (pos = 90; pos >= 0; pos -= 1) { 
            myServo.write(pos);              
            delay(15);                       
          }
        }
      }
      irrecv.resume();
      delay(100);
    }