jeudi 27 avril 2017

Arduino: detecting buttons pressed inside a while loop

I have been trying to write a code to basically add points to a score whenever I pressed a button while a certain amount of time is running down. The problem I am finding is that it doesn't detect when the button is pressed while the time is decreasing, in fact it can only detect when the time starts to decrease and then it doesn't matter at which state the button is it will continue to add to the score. Anyway here is the main code:

void loop() {
  buttonState01 = digitalRead(button01);
  buttonState02 = digitalRead(button02);
  buttonState03 = digitalRead(button03);

if (buttonState01){

time = 3000;
    while(time > 0){
      if (buttonState02){
        score += 10;
        Serial.println(score);
      }
  time--;
Serial.println(time);
    }
  }
}

And here is the full code if needed:

int button01 = 4;
int button02 = 3;
int button03 = 2;

int buttonState01 = 0;
int buttonState02 = 0;
int buttonState03 = 0;

float time;
int score;

void setup() {
  score = 0;

  time = 0;

  pinMode(button01, INPUT);
  pinMode(button02, INPUT);
  pinMode(button03, INPUT);

  Serial.begin(9600);
}

void loop() {
  buttonState01 = digitalRead(button01);
  buttonState02 = digitalRead(button02);
  buttonState03 = digitalRead(button03);

  if (buttonState01){
    time = 3000;
    while(time > 0){
      if (buttonState02){
        Serial.println("Points");
      }
      time--;
      Serial.println(time);  
    }
  }
}

Aucun commentaire:

Enregistrer un commentaire