//https://forum.arduino.cc/t/start-stop-with-delay/908129?
#define PUSHED LOW
#define notPUSHED HIGH
#define LEDon HIGH
#define LEDoff LOW
const byte potPin = A0;
const byte ledPin = 13; //Pin13---[220R]---[A->|-K]---GND
const byte buttonPin = 2; //+5V---[50k internal PU resistor]---[Pin2]---[switch]---GND
byte ledState;
byte buttonStatenew;
byte buttonStateold = notPUSHED;
unsigned int potVal;
unsigned int offTime;
unsigned int offTimeLocked;
unsigned long ledMillis;
unsigned long switchMillis;
//*********************************************************
void setup()
{
Serial.begin(9600);
pinMode (ledPin, OUTPUT);
pinMode (buttonPin, INPUT_PULLUP);
} //END of setup()
//*********************************************************
void loop()
{
//******************************
//is it time to check the switches ?
if (millis() - switchMillis >= 50)
{
//restart the TIMER
switchMillis = millis();
checkSwitches();
}
//******************************
potVal = analogRead(potPin);
offTime = map(potVal, 0, 1023, 1, 60); //set offtime to 1-60
offTime = offTime * 1000; //set offTime to seconds
//******************************
//when the LED is on, is it time to turn it OFF ?
if (ledState == 1 && millis() - ledMillis >= offTimeLocked)
{
//disables TIMER checking
ledState = 0;
digitalWrite(ledPin, LEDoff);
}
//******************************
// Other non blocking code goes here
//******************************
} //END of loop()
//*********************************************************
void checkSwitches()
{
buttonStatenew = digitalRead(buttonPin);
//**********************************
//was there a change in switch state ?
if (buttonStateold != buttonStatenew)
{
//update to the new state
buttonStateold = buttonStatenew;
//*************
//when the LED is OFF, was the switch pushed ?
if (ledState == LEDoff && buttonStatenew == PUSHED)
{
digitalWrite(ledPin, LEDon);
//lock in the delay time
offTimeLocked = offTime;
Serial.print("Delay in ms will be = ");
Serial.println(offTimeLocked);
//enable TIMER checking
ledState = LEDon;
//restart the TIMER
ledMillis = millis();
}
//*************
//when the LED is ON, was the switch pushed ?
else if (ledState == LEDon && buttonStatenew == PUSHED)
{
//cancels the LED timing and turns off the LED
digitalWrite(ledPin, LEDoff);
//disable TIMER checking
ledState = LEDoff;
}
}
} //END of checkSwitches()