Millis() not working

I'm writing a code that switches ON led when there is no input and then goes off after 5seconds. I'm using millis() to offer the delay..
The LED instead just lights up and never goes off. Here is the code.

unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 5000;           // interval at which to blink (milliseconds)

void setup() {
  pinMode(13, OUTPUT);  //Initialize pin 12 as status LED
  pinMode(7, INPUT);    // Our button pin
}

void loop() {

  unsigned long currentMillis = millis();

  if (digitalRead(7) == LOW)   // Switch is closed to start LED timer
  {
    digitalWrite(13, HIGH);  // LED comes On
    previousMillis = currentMillis;
  }

  if (currentMillis - previousMillis >= interval)
  {
    digitalWrite(13, LOW);  // LED goes off
  }
}
const long interval = 5000;           // interval at which to blink (milliseconds)

Wrong datatype.


What value is the external pullup resistor?

You keep getting a new previousMillis all the while the button is pressed. You want to only do that when the button first becomes pressed. See the State Change Example.

unsigned long previousMillis = 0;        // will store last time LED was updated
const unsigned long interval = 5000;           // interval at which to blink (milliseconds)
boolean enableTimer = false;


void setup() {
  pinMode(13, OUTPUT);  //Initialize pin 12 as status LED
  pinMode(7, INPUT);    // Our button pin
}

void loop() {

  unsigned long currentMillis = millis();

  if (enableTimer == false && digitalRead(7) == LOW)   // Switch is closed to start LED timer
  {
    digitalWrite(13, HIGH);  // LED comes On
    previousMillis = currentMillis;
    enableTimer = true;
  }

  if (enableTimer == true && currentMillis - previousMillis >= interval)
  {
    digitalWrite(13, LOW);  // LED goes off
    enableTimer = false;
  }
}

What value is the external pullup resistor?

I'm not using any pull up resistor

Ah, so your input, the one you test to switch the LED just floats when it’s idle? Waiting for a LOW? What value do you think it floats at?

See here, Switches Tutorial:
https://www.gammon.com.au/forum/?id=11955

2017-08-05_20-33-24.jpg

Hi,

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

What model Arduino are you using?

Tom... :slight_smile: