Button and delay in loop?

Hi

How is it possible to read a button when i have a delay in the loop? I want to change a variable when i singlepress the button.

Lets say i have a code like this:

void loop() {
buttonstate = digitalRead(pin);
if(buttonstate == HIGH) {
vari = newvalue;
}
delay(2000);
}

Now if i press the button during those 2 seconds this wont work. So how do i do this? Is it possible?

// Somebody new to arduino :slight_smile:

What is it that you want to do every 2 seconds? Because you need to check the button constantly to catch a press!

long lastcheck=0;

void loop() {
if(millis() - lastcheck > 2000) {
  // do something every 2 seconds
  lastcheck=millis();
}
buttonstate = digitalRead(pin);
if(buttonstate == HIGH) {
vari = newvalue;
}
}

Welcome to Arduino! :slight_smile:

Here is an easy way to check buttons while waitng for a delay to timeout:

int pin = 2;


void loop() {
  // your loop code here
  myDelay(2000);  // call a new delay function that both delays and checks the button states
}


void myDelay(unsigned long duration)
{  
  unsigned long start = millis();

  while (millis() - start <= duration) {
    checkButtons();  // check the buttons 
  }
}


void checkButtons()
{
  int  buttonstate = digitalRead(pin);
  if(buttonstate == HIGH)
  {
    // your code to set vari = newvalue;
  } 
}

void setup(){                 

}

A library version of the above code.

#include <TimedAction.h> //http://www.arduino.cc/playground/Code/TimedAction
#include <Button.h> //http://www.arduino.cc/playground/Code/Button

//handle timing of action()
TimedAction timedAction = TimedAction(2000,action);
//handle button presses on pin 10 wired from pin 10 to switch to GND
Button button = Button(10,PULLUP); //change values to suit your needs

//add your variables here

void setup(){
//add your setup here
}

void loop(){
timedAction.check();
if (button.uniquePress()){ //this only evaluates true one time per press
//button is pressed, do something
//add your 'button pressed' code here
}
}

void action(){
//this function gets called approx. every 2000 millisecond
//add your 'every 2 seconds' actions here
}