Why am I not able to call this method after I push

2019-09-14 23:21发布

问题:

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


标签: arduino