Perform function when second button is pressed within a certain time

Hey guys,

i am trying to create indicators using NEOPIXEL and i wanted to perform a Hazard light pattern where i want to press 1 button , release it and press button 2 (or vice versa) within a certain time to activate that pattern

i tried using millis but was not successful

help would be appreciated
below is the code that is used

but the problem is that even if i press the 2 buttons after more than a minute it still executes the function which it shouldn't do because i declared the interval of 1000millisec(1 sec)

also when viewing in serial monitor the button 1 seems to be always high

const int button1 = 5; // first button pin
const int button2 = 7; // second button pin
const int ledPin = 13; // LED pin
const unsigned long interval = 1000; // time interval in milliseconds

unsigned long firstButtonPressTime = 0; // time when the first button was pressed

void setup() {
  Serial.begin(600);
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  if (digitalRead(button1) == HIGH) {
    firstButtonPressTime = millis();
    Serial.println("button1 ");
  }
  if (digitalRead(button2) == HIGH && millis() - firstButtonPressTime <= interval) {
    executeAnotherFunction();
    Serial.println("****here");
  }
}

void executeAnotherFunction() {
  digitalWrite(ledPin, HIGH);
  delay(1000);
  //digitalWrite(ledPin, LOW);
  Serial.println("***DONE");
}

Using the tags, (click tools bar < code > ), post your code.

Read millis () when you press the first button and assign to a variable . Check millis() again when the second button is pressed . If the difference is within your timing window accept it .

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.