Go Down

Topic: How to monitor a switch's state and do X if switch has remained in state B (Read 1 time) previous topic - next topic

Dane

How to monitor a switch's state and do X if switch has remained in state B for length of time T?

Basically I want to alert the user audibly if a toggle switch remains in and "on" position for longer than 2hrs but don't know how to do it logically.

Would appreciate any tips

Thanks

Arrch

Declare global variable to keep track of the time that the switch has remained in it's position.
Record the edge time for when the switch changed states.
Keep checking for the the time it's been since it's been switched (millis() - timeSwitched) and compare that to your interval time.

Dane


Declare global variable to keep track of the time that the switch has remained in it's position.
Record the edge time for when the switch changed states.
Keep checking for the the time it's been since it's been switched (millis() - timeSwitched) and compare that to your interval time.


Yes that's what I thought initially, but how do I avoid overwriting the timeSwitched with millis() everytime the IF statement checks to see if the switch is still HIGH?

Thanks!

tgm1175

This should get you on the right path.  I think I got all of the conditions but didn't test anything.

Code: [Select]

#define SWITCH_TIMELIMIT 7200000
#define SWITCH_PIN 2

void loop()
{
 static unsigned long switch_timestamp = 0;
 bool switch_state = digitalRead(SWITCH_PIN);

 if(switch_state && switch_timestamp && (millis() - switch_timestamp) >= SWITCH_TIMELIMIT)
 {
   //Do something important here.

   //if you want to reset the warning:
   //switch_timestamp = 0;
 }
 else if (!switch_timestamp && switch_state)
 {
   //The !switch_timestamp is to make sure we don't refresh the timer if the switch remained on.
   //The pin just changed to on, start the timer
   switch_timestamp = millis();
 }
 else if(!switch_state && switch_timestamp)
 {
   //Switch went off, while timer was running, disable the timer
   switch_timestamp = 0;
 }

}



PeterH



Declare global variable to keep track of the time that the switch has remained in it's position.
Record the edge time for when the switch changed states.
Keep checking for the the time it's been since it's been switched (millis() - timeSwitched) and compare that to your interval time.


Yes that's what I thought initially, but how do I avoid overwriting the timeSwitched with millis() everytime the IF statement checks to see if the switch is still HIGH?

Thanks!


Remember the previous state of the switch, and only record the 'start time' when you see the switch change to state B. This is what Arrch refers to as the edge time.
I only provide help via the forum - please do not contact me for private consultancy.

Go Up