How to change this elapsedMillis.h to a global variable? My loop runs only once now

//I have to press the reset button on my Nano to get the output I need. Help me solve.

#include <elapsedMillis.h>

elapsedMillis timeElapsed; //declare global if you don't want it reset every time loop runs

// Pin 5 has an LED connected on most Arduino boards.
int led = 5;
const int S1 = 2;     // the number of the pushbutton pin
const int S3 = 3; 
const int red = 8;
const int green = 11;
// delay in milliseconds between blinks of the LED
unsigned int interval = 100;
int buttonState = 0;         // variable for reading the pushbutton status
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
// state of the LED = LOW is off, HIGH is on
boolean ledState = LOW;

void setup() 
{                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);   
  pinMode(S1, INPUT);
  pinMode(S3, INPUT);
  pinMode(red, INPUT);
  pinMode(green, INPUT);

}

void loop()
{
  buttonState = digitalRead(S1);
  buttonState2 = digitalRead(S3);
  buttonState3 = digitalRead(red);
  buttonState4 = digitalRead(green);
    if (timeElapsed < interval) 
    {       
      timeElapsed =0;       // reset the counter to 0 so the counting starts over...
      Serial.println(timeElapsed);
      Serial.println(interval);
      
      if ((buttonState == HIGH && buttonState2 == LOW && buttonState3 == LOW && buttonState4 == HIGH))
    {
        digitalWrite(led, HIGH);
        delay(1000);
    }
      }
      else
         digitalWrite(led, LOW);
   
}

It's already a global variable. You'll have to be more specific about the problem you're having.

During this condition:

 if (timeElapsed < interval) 
    {       
      timeElapsed =0;       // reset the counter to 0 so the counting starts over...
      Serial.println(timeElapsed);
      Serial.println(interval);
      
      if ((buttonState == HIGH && buttonState2 == LOW && buttonState3 == LOW && buttonState4 == HIGH))
    {
        digitalWrite(led, HIGH);
        delay(1000);
    }
      }
      else
         digitalWrite(led, LOW);

The output is : D5 on my Nano goes HIGH for 1sec, and goes back LOW.
If I change to other logic combinations(which won't trigger D5) and go back to the TRUE logic, the D5 does not trigger. I am forced to press the RESET button on my Nano to get that 1sec HIGH pulse from D5. Now, I don't want to press the RESET button. Each time I form the correct logic combo,I want D5 to produce a HIGH pulse. How could I achieve this?

Hi,
Welcome.
Fst the error I saw in your project:
You are using serial monitor but not initialized in setup().
Missing Serial.begin(xxxxx); xxxx can be 9600, 115200, etc..

Did you intend to write this:
if (timeElapsed >= interval)

The way it is written: "If (the interval has not elapsed) {reset the timer}"

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