当我想让伺服器无限旋转一次时

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

我是 Arduino 的新手。我想做一个简单的设置,按下遥控器上的一个按钮将使舵机旋转90度并返回0。

这是我的代码:

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

然而,当我按下指定的按钮时,舵机会在 0 度和 90 度之间无限摆动,但我只希望它在每次按下按钮时这样做一次。我该怎么做?

您需要添加行

irrecv.resume();

如果在最终延迟之前循环结束,以便清除结果并开始寻找新信号。

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);
}