Author Options:

How can I use a button to control a loop within a specific time limit? Answered

Hello everyone,

in my code below I have a button that initiates several actions. Initially it is set to LOW and when the button is HIGH several actions occur. I would like to add a time limit of 3 seconds so if the button stays LOW after that a different set of actions will occur. I tried using the if/else functions. Any suggestions will be appreciated!




Servo s2; int BUTTON = 2; int COUNT = 1; int buzzerPin = 8; int counter;

void setup() {

Serial.begin(9600); pinMode(10, INPUT); pinMode(13, OUTPUT); pinMode(12, OUTPUT); s2.attach(5); } void loop() {

unsigned long start_time; unsigned long stop_time; s2.write(6);

if (Serial.available() > 0) { char data = Serial.read(); // reading the data received from the bluetooth module switch (data) { { case '1':

start_time = millis(); Serial.println(" "); Serial.println(" Go...Go.. "); for (counter = 0; counter < 3; ++counter) { switch (COUNT); int servo = random(5); while (digitalRead(BUTTON) == LOW) { digitalWrite(13, HIGH); digitalWrite(12, LOW); s2.write(90); delay(10); } if (digitalRead(BUTTON) == HIGH) { Serial.write ("*S"); tone(buzzerPin, 600); delay(50); noTone(buzzerPin); digitalWrite(13, LOW); digitalWrite(12, HIGH); s2.write(6); delay(600); COUNT ++; Serial.print("You hit "); Serial.println(COUNT); } } }

Serial.println(" "); Serial.println(" Finished: "); Serial.println("Your result is: "); Serial.print(COUNT); Serial.print(" Target in "); stop_time = millis(); Serial.print(stop_time - start_time); Serial.println(" Time"); Serial.println(" "); if (COUNT > 0) { COUNT = 0; } } } }


The forums are retiring in 2021 and are now closed for new topics and comments.

1 year ago

I'm a little rusty on this, but I think you want to use either a timer or hardware interrupt that does the counting in the background and then jumps out of the main routine when the time limit is met.