Go Down

Topic: millis madness (Read 517 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
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy