EDIT:Why isn't my button responding in the code?

Thanks for the help earlier. Ive written a better program and used less delays(I need to read up on 'non block timing' but still am having trouble with the button.

#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

int duration;
String msg="Enter a time between 5 and 30: "; 
bool k= false; 
int buzzer= 9;
int t=1000;//delay 1 second
int ledR=8;
int resetB= 7;
bool buttonState = false;
bool done= false;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(ledR,OUTPUT);
pinMode(resetB,INPUT);
pinMode(buzzer,OUTPUT);
lcd.begin(16, 2);
Serial.println(msg);
}

void loop() {
buttonState= digitalRead(resetB);  

Serial.available()==0;
duration=Serial.parseInt();
buttonState=false;
while(duration>=5 && duration<=30 && buttonState==false) {
  for(duration; duration>0; duration--){
    lcd.clear();
    lcd.println(duration);
    delay(t);
    done= true;  
  }
buttonState=false;
  if(done== true && buttonState==false) {
    lcd.clear();
    lcd.println("Times up");
    digitalWrite(buzzer,HIGH);
    digitalWrite(ledR,HIGH);
    tone(9, 500);
    delay(10000);//gives 10 seconds to press reset
    k= true;
  }
  if(k==true){
    lcd.clear();
    Serial.println("Press the damn button");
    tone(9, 1000);  
  }
}

}

The vast majority of the time your code is sitting in a delay(), and can't see anything at all.

2 Likes

Do not use delay( ) or while( ) or do( ) in your sketches unless they are set up very short periods of time.

1 Like

here are two alernatives:

adding checking the button in each and every while-loop and do loop still avoiding each delay()
very uncomfortable to add the button-checking

learning to write code that uses non-blocking timing (which means to be able to avoid delay() and still doing things only after a certain time

best regards Stefan

1 Like

Hello blackbush
Take a view here.

1 Like

Non blocking timing is something ive never heard of. Thank you!

This code toggles a LED every 500ms using a non blocking TIMER.


  //***********************************************         heartbeat T I M E R
  //time to toggle the heartbeat LED ?
  if (millis() - heartbeatMillis >= 500)
  {
    //restart the TIMER
    heartbeatMillis = millis();

    //toggle LED
    digitalWrite(heartbeatLED, !digitalRead(heartbeatLED));
  }

Here is a tutorial that explains the principle of non-blocking timing

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