Why am I not able to call this method after I push a button?

末鹿安然 提交于 2019-12-12 04:15:15

问题


I'm using a pushbutton as a toggle switch. Press it and it does "stuff A." Press it again and it does "stuff B." Why am I not able to call my method checkButtons_slow()?

int prev = 0;
int current = 0;
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();
    //test: ZServo.write(110);
    delay(500); //half a second
  }
  if(current == 0 && prev == 1) {
    ZServo.write(80);
    delay(500); //half a second
  }
  prev = current;
}

Here's my method:

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

So the commented out //test: ZServo.write(110); works. What am I missing with the checkButtons_slow();?


回答1:


If you change void loop() to this then it will work to toggle the method on and off.

void loop() {
  if (digitalRead(3) == LOW) {
    num_presses++;
    delay(500);
  }
  if ((num_presses % 2) == 0) {
    //even
    checkButtons_slow();
  }
  else if(num_presses == 0) {
    ZServo.write(90);
  }
  else {
    ZServo.write(85);
  }
}


来源:https://stackoverflow.com/questions/44891298/why-am-i-not-able-to-call-this-method-after-i-push-a-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!