im new here, currently i'm working a timer project with only 1 button to start timer & increase time if current time not end .
exp :on timer time set 20sec, if within 20sec i press again the button it will add another 20sec on current time.
but i try many way it cant work
below my code please help & advise me Thanks:
#define led 13
boolean Rled = false;
long current = 0;
long RoffTime = 0;
boolean Rledon = false;
boolean Rledoff = false;
1- preset 20sec once press led will on for 20sec
2- if within 20sec i press again it will extend another 20sec on the current time (example: current time balance 10sec it add 20sec = 30sec) same go if i press the button 3 times = 20sec x 3 + current balance time.
const byte ButtonPin = 2;
unsigned long StartTime = 0;
unsigned long Interval = 0;
void setup()
{
pinMode(ButtonPin, INPUT);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop()
{
unsigned long currentMillis = millis();
if (digitalRead(ButtonPin) == HIGH)
{
if (StartTime != 0)
{
// Timer already running
Interval += 20000UL; // Increase the timer interval by 20 seconds
}
else
{
StartTime = currentMillis;
Interval = 20000UL; // Start with a 20-second interval
digitalWrite(LED_BUILTIN, HIGH); // LED on
}
}
// If the timer is running, test to see if the timer has expired
if (StartTime != 0 && currentMillis - StartTime >= Interval)
{
// Timer has finished
digitalWrite(LED_BUILTIN, LOW); // LED off
StartTime = 0; // Timer not running
}
}