How to detect button input within a given timeframe

I have a project where a random of 1 of 5 LEDs would light up and when a button corresponding to the LED that lit up is pressed, it would turn off the LED and repeat.

  //LED pin variables
const int bLED = 2;
const int gLED = 4;
const int rLED = 6;
const int yLED = 8;
const int wLED = 10;
const int gsLED = 12;
const int goLED = 13;
  //Button pin variables
const int bButton = 3;
const int gButton = 5;
const int rButton = 7;
const int yButton = 9;
const int wButton = 11;
  //Button reading states
int bButtonState;
int gButtonState;
int rButtonState;
int yButtonState;
int wButtonState;

int cooldown = 5000;
int LEDinterval = 5000;
long prebLED = 0;
long pregLED = 0;
long prerLED = 0;
long preyLED = 0;
long prewLED = 0;

void setup() {
  // put your setup code here, to run once:
  //LED pin modes
pinMode(bLED, OUTPUT);
pinMode(gLED, OUTPUT);
pinMode(rLED, OUTPUT);
pinMode(yLED, OUTPUT);
pinMode(wLED, OUTPUT);
  //Button pin modes
pinMode(bButton, INPUT);
pinMode(gButton, INPUT);
pinMode(rButton, INPUT);
pinMode(yButton, INPUT);
pinMode(wButton, INPUT);
Serial.begin(9600);
//Game starts
  digitalWrite(gsLED, HIGH);
  delay(2000);
  digitalWrite(gsLED, LOW);
}

void loop() {
  bButtonState = digitalRead(bLED);
  gButtonState = digitalRead(gLED);
  rButtonState = digitalRead(rLED);
  yButtonState = digitalRead(yLED);
  wButtonState = digitalRead(wLED);

  unsigned long currentMillis = millis();
  randomSeed(analogRead(A0));
  int l2l = random(0,5);
  if (l2l == 0) {
    digitalWrite(bLED, HIGH);
    if (currentMillis - prebLED >= LEDinterval) { //within a span of 5s, if...
      prebLED = currentMillis;
      if (bButtonState == 1) {
        digitalWrite(bLED, LOW);
        Serial.println("pressed");
        delay(cooldown - 200);
        return;
      }
      else if (bButtonState == 0) {
        digitalWrite(bLED, LOW);
        Serial.println("not pressed");
        delay(cooldown - 200);
        return; //where program is supposed to end
      }
    }
  }
  else if (l2l == 1) {
    digitalWrite(gLED, HIGH);
    if (currentMillis - pregLED >= LEDinterval) { //within a span of 5s, if...
      prebLED = currentMillis;
      if (gButtonState == 1) {
        digitalWrite(gLED, LOW);
        Serial.println("pressed");
        delay(cooldown - 200);
        return;
      }
      else if (gButtonState == 0) {
        digitalWrite(gLED, LOW);
        Serial.println("not pressed");
        delay(cooldown - 200);
        return; //where program is supposed to end
      }
    }
  }
  else if (l2l == 2) {
    digitalWrite(rLED, HIGH);
    if (currentMillis - prerLED >= LEDinterval) { //within a span of 5s, if...
      prerLED = currentMillis;
      if (rButtonState == 1) {
        digitalWrite(rLED, LOW);
        Serial.println("pressed");
        delay(cooldown - 200);
        return;
      }
      else if (rButtonState == 0) {
        digitalWrite(rLED, LOW);
        Serial.println("not pressed");
        delay(cooldown - 200);
        return; //where program is supposed to end
      }
    }
  }
    else if (l2l == 3) {
    digitalWrite(yLED, HIGH);
    if (currentMillis - preyLED >= LEDinterval) { //within a span of 5s, if...
      preyLED = currentMillis;
      if (yButtonState == 1) {
        digitalWrite(yLED, LOW);
        Serial.println("pressed");
        delay(cooldown - 200);
        return;
      }
      else if (yButtonState == 0) {
        digitalWrite(yLED, LOW);
        Serial.println("not pressed");
        delay(cooldown - 200);
        return; //where program is supposed to end
      }
    }
  }
    else if (l2l == 4) {
    digitalWrite(wLED, HIGH);
    if (currentMillis - prewLED >= LEDinterval) { //within a span of 5s, if...
      prewLED = currentMillis;
      if (wButtonState == 1) {
        digitalWrite(wLED, LOW);
        Serial.println("pressed");
        delay(cooldown - 200);
        return;
      }
      else if (wButtonState == 0) {
        digitalWrite(wLED, LOW);
        Serial.println("not pressed");
        delay(cooldown - 200);
        return; //where program is supposed to end
      }
    }
  }
}

Currently I have problems with the timing, how to detect input within a span of 5s
I also have issues with ending the sketch, I had someone consult using break; but that didn't work.
My sketch is pretty repetitive so bare with me.

do you have external pullup or pulldown resistors?
what's your circuit?

@frenchbaguettes
Your code contains a five almost identical code blocks. Repeating the code - is a bad programming style.

if you used arrays for buttons and LEDs - the code became five times shorter and it would be easier for you to work with buttons

Why not read "bButton"?

Have I misunderstood something?

to help out, consider this code structure:

(typed here, so look more at the idea behind the structure, not sure it compiles as I might have some spelling mistakes or whatever)

const byte ledPins[] = {2, 4, 6, 8, 10};
const byte buttonPins[] = {3, 5, 7, 9, 11};
const byte numberOfItems = sizeof ledPins; // ledPins is a byte type so each entry uses up 1 byte => number of bytes in the array == count of pins
const byte getStartedLedPin = 12;
const unsigned long maxWait = 5000ul;

unsigned long startTime;
byte selectedLedIndex;
bool waitingForClick = false;


void setup() {
  for (byte aLedPin : ledPins) pinMode(aLedPin, OUTPUT);
  pinMode(getStartedLedPin, OUTPUT);

  for (byte aButtonPin : buttonPins) pinMode(aButtonPin, INPUT_PULLUP);

  // make sure we get a bit more random
  randomSeed(analogRead(A0));

  Serial.begin(115200); Serial.println();
  //Game starts
  digitalWrite(getStartedLedPin, HIGH);
  delay(2000);
  digitalWrite(getStartedLedPin, LOW);
}

void loop() {
  if (waitingForClick) {
    if (millis() - startTime >= maxWait) {
      // damned timeout.
      // do something to show you lost and whatever counting you want to do

      // -----
      // some code goes here
      // -----

      // we will need to pick a new LED so we turn off the current led
      digitalWrite(ledPins[selectedLedIndex], LOW);
      // and let the loop do its magic and select a new led at the next spin
      waitingForClick = false;
    } else {
      // still within the right wait time
      // check if one button has been pressed
      for (byte i = 0; i < numberOfItems; i++) {
        if (digitalRead(buttonPins[i] == LOW)) {
          // that button is pressed check if this is the correct one
          if (i == selectedLedIndex) {
            // BINGO, the right button was selected
            // do something to show you won and whatever counting you want to do

            // -----
            // some code goes here
            // -----

            // we will need to pick a new LED so we turn off the current led
            digitalWrite(ledPins[selectedLedIndex], LOW);
            // and let the loop do its magic and select a new led at the next spin
            waitingForClick = false;
          } else {
            // wrong button pressed...
            // do something to show you got it wrong and whatever counting you want to do

            // -----
            // some code goes here
            // -----

            // we will need to pick a new LED so we turn off the current led
            digitalWrite(ledPins[selectedLedIndex], LOW);
            // and let the loop do its magic and select a new led at the next spin
            waitingForClick = false;
          }
        }
      }
    }
  } else {
    // we need to pick a random LED
    selectedLedIndex = random(0, numberOfItems); // a number between 0 and numberOfItems-1 that we use as an index
    digitalWrite(ledPins[selectedLedIndex], HIGH);
    startTime = millis();
    waitingForClick = true;
  }
}

the idea is that you don't have any blocking code and you let the loop do the waiting for you.

There is a little state machine driven by the boolean waitingForClick.

  • if this is false then the loop need to select and show a random led and record the start time.
  • if it is true then it means we are in the waiting phase and so you check for timeout (as you know the start time and current time it's easy to know for how long you have been waiting) or if there is a button press and do the right thing if such an event occurs.

I used arrays to make it easier to do all the repetitive work and used for loops.

makes sense?

that was my mistake, I'll fix that :slight_smile:

so I tried this, I had some issues

const byte ledPins[] = {2, 4, 6, 8, 10};
const byte buttonPins[] = {3, 5, 7, 9, 11};
const byte numberOfItems = sizeof ledPins; // ledPins is a byte type so each entry uses up 1 byte => number of bytes in the array == count of pins
const byte startLedPin = 12;
const byte endLedPin = 13;
const unsigned long maxWait = 7000ul;
long waitTime = maxWait;
long lastTimeout = 0;

unsigned long startTime;
byte selectedLedIndex;
bool waitingForClick = false;


void setup() {
  for (byte aLedPin : ledPins) pinMode(aLedPin, OUTPUT);
  pinMode(startLedPin, OUTPUT);
  pinMode(endLedPin, OUTPUT);

  for (byte aButtonPin : buttonPins) pinMode(aButtonPin, INPUT);

  // make sure we get a bit more random
  randomSeed(analogRead(A0));

  Serial.begin(9600); Serial.println();
  //Game starts
  digitalWrite(startLedPin, HIGH);
  delay(2000);
  digitalWrite(startLedPin, LOW);
}

void loop() {
  if (waitingForClick) {
    if (startTime - lastTimeout >= waitTime) {
      // damned timeout.
      // do something to show you lost and whatever counting you want to 
      lastTimeout = startTime;
      digitalWrite(endLedPin, HIGH);
      delay(1500);
      digitalWrite(endLedPin, LOW);
      delay(1000);
      Serial.println("timeout");
      // -----
      // some code goes here
      // -----

      // we will need to pick a new LED so we turn off the current led
      digitalWrite(ledPins[selectedLedIndex], LOW);
      // and let the loop do its magic and select a new led at the next spin
      waitingForClick = false;
    } else {
      for (byte i = 0; i < numberOfItems; i++) {
        if (digitalRead(buttonPins[i]) == 0) {
          if (i == selectedLedIndex) {
            digitalWrite(startLedPin, HIGH);
            delay(500);
            digitalWrite(startLedPin, LOW);
            Serial.println("correct");
            waitTime = maxWait - 150;           
            digitalWrite(ledPins[selectedLedIndex], LOW);
            waitingForClick = false;

          } else {
            digitalWrite(endLedPin, HIGH);
            delay(1500);
            digitalWrite(endLedPin, LOW);
            delay(1000);
            Serial.println("wrong");
            digitalWrite(ledPins[selectedLedIndex], LOW);
            waitingForClick = false;
          }
        }
      }
    }
  } else {
    // we need to pick a random LED
    selectedLedIndex = random(0, numberOfItems);
    digitalWrite(ledPins[selectedLedIndex], HIGH);
    startTime = millis();
    waitingForClick = true;
  }
}

Timing: the sketch doesn't really wait 7s after the first random LED lit up before immediately printing 'wrong' sometimes there's not even a random LED that's lit up yet and already 'wrong' is printed out.
(making the LED on pin13 blink continuously while the rest of the LEDs blink randomly)

Button input: I press the corresponding button right after the random LED lights and it doesn't recognize the input as correct, instead displays as wrong.
(making the LED on pin13 blink continuously while the rest of the LEDs blink randomly)

And for some reason, when the random blue LED (pin 2, ledPins[0]) lights up, the sketch doesn't wait for an input but immediately prints 'correct'.

also could you explain this line of code for me
(sorry I made a new post with the same topic including your code, I wasn't aware of the regulation)

this is called a for range loop. the variable aButtonPin will go through all the values of the buttonPins container (array) and execute the statement that is after the for()

it's kinda the same as the more classical
for (int i = 0; i<5; i++) pinMode(buttonPins[i], INPUT_PULLUP);
but you don't have to worry about knowing the size of the array


You can use the built in pullup resistor of your arduino, so wire the buttons this way:

arduino pin --- button --- GND

if your button as 4 "legs", use diagonally opposed legs for connecting the arduino pin and GND this way you are always sure to not connect the wrong legs.

as I said, the code was typed here and not tested (bouncing for example could be an issue), it's more the structure of the code you would need to understand

I had a look at my code, I have a typo in what I typed here:

if should obviously read

        if (digitalRead(buttonPins[i]) == LOW) {

the code needs to handle the release of the button and bouncing. Best would be to use a button library. you can check Button in easyRun or OneButton or (very complete) Toggle from @dlloyd.