Writing an 'if at any point during the loop' statement

Hi all,

I'm new to arduino, and programming so any help and patience is much appreciated!

What I'm trying to do is have a red LED light go on every 15 seconds (looping), unless a button is pushed, in which case, a green LED light goes on and the loop resets

my problem is that im not sure whether i should be using an if or while statement (or somehow both?) to get the button press to work during any time during the loop.
what i have right now is:

const int redLed = 2;
const int greenLed = 9;
const int keyPin = 13;

void setup() {
pinMode (redLed, OUTPUT);
pinMode (greenLed, OUTPUT);
pinMode (keyPin, INPUT);
}

void loop() {
// put your main code here, to run repeatedly:
digitalWrite (redLed, LOW);
digitalWrite (greenLed, LOW);

if (digitalRead(keyPin) == HIGH )
{
digitalWrite (greenLed, HIGH);
delay(500);
}
else
{
delay(15000);
digitalWrite(redLed,HIGH);
delay(500);
}
}

Get rid of the calls to delay() if you want your switch closures to be responsive.
Take a look at the blink without delay example, without delay.

/* My third code
 * I have a switch to light a led 
 * Push the switch => LED turns on
 * Push the switch again => LED turns off
 */

 int switchPin = 8;
 int ledPin = 11;
 boolean lastButton = LOW;
 boolean ledOn = false;
boolean currentButton = LOW;

 boolean debounce(boolean last)
 {
  boolean current = digitalRead(switchPin);
  if (last != current)
  {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
 }
 
void setup() {
  // put your setup code here, to run once:
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
}


void loop() {
  // put your main code here, to run repeatedly:
  
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH) 
  {
   // do stuff if the condition is true
  ledOn = !ledOn;
  } 
   lastButton = currentButton;
  digitalWrite(ledPin, ledOn);
}

here is my code that I wrote

With the buttons you have to do something called debouncing.

When you push the bottom the signal doesn't go from high to low OR low to high straight away. it jumps between for a bit and then stabilises. So you have to deal with this "problem" in your program!!

The code that i put is doing it in software (inexpensive way)

please modify it to suit your project :slight_smile: