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:
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);
}
}
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.
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.
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
}