当我尝试更新按钮的状态时,为什么我的按钮作为切换不起作用?

时间:2017-07-05 15:09:16

标签: arduino toggle

当我按下按钮后尝试更改按钮的状态时,没有任何作用。我使用行prev = current;

执行此操作
#include <Servo.h>;

//HIGH not pressed
//LOW pressed

int pushD3 = 3;
int pushD4 = 4;
int pushD5 = 5;
int pushD6 = 6;
int val4 = 0;
int val5 = 0;
int ledPin = 13;
int prev = 0;
int current = 0;
Servo ZServo;

void setup() {
  ZServo.attach(9);
  pinMode(pushD3, INPUT_PULLUP);
  digitalWrite(3, HIGH);
  pinMode(pushD4, INPUT_PULLUP);
  digitalWrite(4, HIGH);
  pinMode(pushD5, INPUT_PULLUP);
  digitalWrite(5, HIGH);
  pinMode(pushD6, INPUT_PULLUP);
  digitalWrite(6, HIGH);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(3) == LOW) {
    current = 1 - current;
  }
  if (current == 1 && prev == 0) {
    checkButtons_slow();
    delay(100);
  }
  if (current == 0 && prev == 1) {
    //ZServo.write(110);
    delay(500); //half a second
  }
  prev = current;
}

void checkButtons_slow() {
  val4 = digitalRead(pushD4);
  val5 = digitalRead(pushD5);
  if (val4 == LOW) {
    ZServo.write(87);
  } else if (val5 == LOW) {
    ZServo.write(99);
  } else {
    ZServo.write(91); //GUESSED ON 92; SHOULD TECHNICALLY BE 90
  }
}

2 个答案:

答案 0 :(得分:0)

即使未按下按钮,也会更新切换状态。这就是逻辑不起作用的原因。您还需要跟踪按钮被释放的时间以切换按钮逻辑。

您可能也是开关弹跳的下一个受害者。典型的开关不会从打开到关闭干净,并且在推动(和释放)时可以产生小的,快速的打开/关闭信号。虽然这不会影响简单的按下/按下按钮操作,但它对于多个状态切换是一种杀手。

避免这种情况的一种简单方法是限制读取开关的速率。我发现30ms的速率非常好。

int last_time = 0;
bool was_pushed = false;

void loop() {

  if (millis() - last_time > 30)  // filter out signal bounce.
  {
    last_time = millis();
    if (digitalRead(3) == LOW) 
    {
      if (!was_pushed)            // prevent toggling until button is released.      
        current = !current;
      was_pushed = true;  
    }
    else
    {
      was_pushed = false;
    }
    if (current != prev)
    {
       prev = current;           // keep the previous toggle state only on change.
       if (current) 
       {
         checkButtons_slow();
         delay(100);
       }
       else
       {
         //ZServo.write(110);
         delay(500); //half a second
       }
    }
  }
}

答案 1 :(得分:0)

我发现你的实现和迈克尔有点混乱,为什么不这样做:

bool state = false;
bool buttonPressed = false;
void loop(){
    if (digitalRead(3) == LOW && !buttonPressed){
        state=!state;
        buttonPressed = true;
    }
    if(digitalRead(3) == HIGH){
        buttonPressed = false;
    }

    // Then your logic
    if (state) {
    checkButtons_slow();
    delay(100);
    } else{
        //ZServo.write(110);
        delay(500); //half a second
    }
}