Hello guys.
I used one button to implement various functions. I made One Click, Double Click, and Long Press using the button. And now I'm going to make a function that cancels the running function by pressing the button.
void loop() {
Button();
}
//========================================================================================================================
void Button(){ //Button function
if(btn_flag && ((millis()-time)>1000) && !start_flag){ //once click button
Serial.println("one click");
Function_1(); //Run function 1
btn_flag = false;
}
else if(btn_flag && start_flag){
//Blinking at power-on
digitalWrite(led1, HIGH);
digitalWrite(led2, HIGH);
delay(100);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
delay(100);
digitalWrite(led1, HIGH);
digitalWrite(led2, HIGH);
delay(100);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
start_flag = false;
btn_flag = false;
}
if(digitalRead(sw) == HIGH){ //press button
if(btn_flag && ((millis()-time)<1000) ){ // double click button
Serial.println("double click");
Function_2(); //Run function 2
btn_flag = false;
}
else {
time = millis();
btn_flag = true;
}
delay(10);
while(digitalRead(sw) == HIGH){ // Press 3 seconds to enter the sleep mode.
if((millis()-time) > 3000){
start_flag = true;
sleepNow();
return;
}
}
delay(10);
}
}
And this is the result of pressing the button. I tested it with LED now, but I will use transistor and motor etc later.
void Function_1(){ //once click : LED 5sec ON
digitalWrite(led1, HIGH);
delay(500);
while(digitalRead(led1) == HIGH) //I made this code for cancellation function. But it doesn't work properly.
{
if(digitalRead(sw) == HIGH)
{
Stop();
break;
}
else if(digitalRead(sw) == LOW)
{
delay(5000); //5sec ON
digitalWrite(led1, LOW);
break;
}
}
}
void Function_2(){ //double click : blinking 5times
for(int i = 0; i <5; i++){
digitalWrite(led2, HIGH);
delay(500);
digitalWrite(led2, LOW);
delay(500);
}
}
//========================================================================================================================
void Stop() //Cancel Running Function
{
Serial.println("STOP");
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
}
I've tried use interrupt. However, if I press the button and run the function, the interrupt runs together and ends at the same time as it starts.
I might have miswritten it because I used a translator. Thank you for reading.
I'd really appreciate it if you could tell me how to fix it...!!