Currently I am using OneButton.h library to code my push button project.
When I press button1, it will loop for 10sec and print TRIG, and after that it will break the loop.
However, now I want to program it where when I pressed button1, it will jump to void(singleclick)
function, but right now, during the 4th seconds (anytime before 10th sec) , I pressed other button, thus Arduino will break the 10sec loop and run other function.
Thus, I need help how to make sure Arduino actively read other button and when pressed, it will break the current loop/function to other related functions.
#include <OneButton.h>
OneButton button1(2, true);
OneButton button2(3, true);
OneButton button3(4, true);
OneButton button4(5, true);
int led1=12;
int led2=11;
int led3=10;
int led4=9;
int flag;
unsigned long mode;
void setup()
{
Serial.begin(9600);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led3,OUTPUT);
pinMode(led4,OUTPUT);
button1.attachClick(singleclick1);
button1.attachLongPressStop(longclick);
button2.attachClick(singleclick2);
button3.attachClick(singleclick3);
button4.attachClick(singleclick4);
digitalWrite(led1,HIGH);
digitalWrite(led2,HIGH);
digitalWrite(led3,HIGH);
digitalWrite(led4,HIGH);
}
void loop()
{
button1.tick();
delay(20);
button2.tick();
delay(20);
button3.tick();
delay(20);
button4.tick();
delay(20);
Serial.println("No button");
}
void singleclick1()
{
mode=millis();
flag=1;
while(flag==1)
{
Serial.println("button1");
digitalWrite(led1,HIGH);
digitalWrite(led2,LOW);
digitalWrite(led3,LOW);
digitalWrite(led4,LOW);
if(millis()-mode>5000)
{
Serial.println("TRIG");
flag=0;
button2.tick();
delay(20);
button3.tick();
delay(20);
button4.tick();
delay(20);
return;
}
}
}
void singleclick2()
{
Serial.println("button2");
digitalWrite(led1,LOW);
digitalWrite(led2,HIGH);
digitalWrite(led3,LOW);
digitalWrite(led4,LOW);
}
-
You could run a timer that toggles a flag after 10 seconds. Then the loop would check that flag on each iteration.Kwasmich– Kwasmich2021年03月02日 07:15:19 +00:00Commented Mar 2, 2021 at 7:15
1 Answer 1
This is just a rough, incomplete and untested code.
void singleclick1() { startTimer = true; } // this only sets a flag
void singleclick2() { runTimer = false;} // this only clears a flag
void loop() {
button1.tick();
button2.tick();
if startTimer { // this occurs once every click 1
mode = millis();
runTimer = true;
startTimer = false; // run this block only once every click 1
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW );
digitalWrite(led3, LOW );
digitalWrite(led4, LOW );
}
unsigned long currentMillis = millis();
if (currentMillis - mode > 10000) {
runTimer = false; // 10 second timer expired
}
if (runTimer) {
Serial.println("TRIG");
}
else {
// optional stuff to do
}
}
-
Thank you so much!Peterhan123– Peterhan1232021年03月04日 01:13:58 +00:00Commented Mar 4, 2021 at 1:13