当我按下遥控器上的按钮时,我试图从伺服器获得连续(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
}
}
答案 0 :(得分:0)
解决问题的一种方法是检查是否存在&#34;按钮按下&#34;更深入loop()
。按下按钮的检查按里面您的移动for
循环以立即捕获更改。看起来你可能有两个启动码(?),所以你可能不得不改变下面的if
语句,但希望我演示如何检查条件以及#34;继续前进&#34;在下面的代码示例中。
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
}
}
}
}