Go Down

Topic: Using the millis() function with button (Read 282 times) previous topic - next topic

kjpapercup

Hi, I am currently doing a project using a button , an led . i am having some trouble coding . My objective is that if the button is press within 5 sec the led will blink for 1 sec 3 time . and if the button is not pressed (after 5 sec ) the led will blink for 500ms 3 times .
here is my code:
Code: [Select]

int led=4;
unsigned long previousMillis = 0;
const long interval = 5000;
int btn=5;
int btnstat;
int i=0;
int x=0;

void setup()
{
  pinMode(led, OUTPUT);
  pinMode(btn,INPUT_PULLUP);
}

void loop()
{
   digitalWrite(led,HIGH);
    delay(5000);
    digitalWrite(led,LOW);
 unsigned long currentMillis = millis();

if (currentMillis-previousMillis<interval)
{
    previousMillis=currentMillis;
  btnstat=digitalRead(btn);
  if (btnstat==LOW)
  {
 
    for(x=0;x<3;x=x+1)
    {
    digitalWrite(led,HIGH);
      delay(1000);
    digitalWrite(led,LOW);
    delay(1000);
     
    }

  }

}
  else
  {
 
     
    for(i=0;i<3;i=i+1)
    {
    digitalWrite(led,HIGH);
    delay(500);
    digitalWrite(led,LOW);
      delay(500);
     
     
    }
 
  }
 

devcoder

wait, so what problem do you have?
error messages?

kjpapercup

I am using this millis function in another program so this is just a simulation( the led on for 5 sec at the start of the program simulates my other program ) . when i reach the if else function if just skip to the else function without having the option to press the button.

PaulS

Code: [Select]
int led=4;
What does this mean? ledPin means something.

Code: [Select]
    delay(5000);
    digitalWrite(led,LOW);
 unsigned long currentMillis = millis();

delay() and millis() rarely belong in the same code. currentMillis is a stupid name. The variable holds the time that some event happened. The name of the variable should reflect that event. In this case, now is a MUCH more appropriate name.

You MUST determine when the switch BECOMES pressed, NOT when the switch IS pressed. THAT is the event that is important.
The art of getting good answers lies in asking good questions.

devcoder

you can adapt the code from this section:
Code: [Select]

 if (digitalRead(buttonPin) == LOW)
      {
        pulseBegin = millis();
        while (digitalRead(buttonPin) == LOW){} //do nothing while push button is being pressed
        pulseWidth = millis()-pulseBegin; //record pulse width of button being pressed   
        if (pulseWidth <5000){} //turn off if the button is pressed less than a second
      }

Go Up