Arduino按钮麻烦

时间:2015-02-18 04:25:47

标签: arduino

我只是想让它在按钮状态很高时点亮。我究竟做错了什么???我一直随意打开和关闭它。提前谢谢。

const int buttonPin = 2; 
const int ledPin =  13;
int buttonState = 0;
boolean curstat = LOW;
boolean lasstat = LOW;
boolean ledState = LOW;


void loop(){
 curstat = digitalRead(buttonPin);

if (curstat == HIGH && lasstat == LOW){
 Serial.println("pressed");
delay(1);
bucount = bucount + 1;
Serial.println(bucount);
myservo.write(180);
delay(1);
 digitalWrite(ledPin, HIGH); 
  delay(1);


}
else if(curstat == LOW && lasstat == HIGH){ 
  Serial.println("relased");
  delay(1);
  myservo.write(89);
  delay(1);
   digitalWrite(ledPin, HIGH); 
  delay(1);
}
else if(curstat == LOW && lasstat == LOW){
  Serial.println("nothing has happened");
  digitalWrite(ledPin, LOW);
delay(1);
myservo.write(90);
  delay(1);

}
}

1 个答案:

答案 0 :(得分:0)

首先,您需要在设置中声明输入和输出:

void setup(){
    pinMode(buttonPin, INPUT)
    pinMode(ledPin, OUTPUT)
}

另一个重要的事情是你读过curstat,但你永远不会改变lasstat,所以Arduino永远不会理解以前的状态,考虑添加这段代码:

if (curstat == HIGH && lasstat == LOW){
    Serial.println("pressed");
    delay(1);
    digitalWrite(ledPin, HIGH); 
    delay(1);
    lasstat = HIGH;
}

这样,您只需输入一次if语句,即使您按下按钮的时间过长也是如此。别忘了在其他if语句中改变lasstat。

侨!