Go Down

Topic: millis madness (Read 497 times) previous topic - next topic

N2scouting

I am trying to build a simple on delay timer. I would like to press and hold a pushbutton for 5 seconds and then a LED would come on.
Code: [Select]

int ledPin =  13;     
int buttonPin = 2;
int ledState = LOW;     
int state=0;
long previousMillis = 0;     
long interval = 5000;

void setup() {
    pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT); 
}

void loop()
{
    unsigned long currentMillis = millis();
  state=digitalRead(buttonPin);

  if (state==HIGH) 
  {
    if(currentMillis - previousMillis > interval )
    previousMillis = currentMillis;     
   
    if (ledState == LOW)
      ledState = HIGH;}
      else{
      ledState= LOW;
 
    digitalWrite(ledPin, ledState);
  }
}

liudr


I am trying to build a simple on delay timer. I would like to press and hold a pushbutton for 5 seconds and then a LED would come on.


And? (hint: anything wrong?)

N2scouting

The LED never comes on.

nickvd

I fixed the indenting to make the code a little clearer...
Code: [Select]
void loop()
{
unsigned long currentMillis = millis();
state=digitalRead(buttonPin);

if (state==HIGH) 
{
if(currentMillis - previousMillis > interval )
previousMillis = currentMillis;     

if (ledState == LOW)
ledState = HIGH;
}
else
{
ledState= LOW;
digitalWrite(ledPin, ledState);
}
}


The only time you call digitalwrite on the led is when it's low.  You then set it low... 

liudr

You did most of the OP's work :)

OP, please re-do your logic now that nickvd has properly indented your code. Just give it a try.

Go Up