If Analogue value holds for set time do this

HI I've been reading around and I'm unsure as to a appropriate approach to this issue. In essence i am trying to achieve a switch in the for loop. I wish to have a statement in my void loop where if an analogue sensor remains equal to or more than a certain value for 5 seconds it would make a boolean true. that boolean would then be used to trigger another if statement which would then do "something" and then write the boolean back to false. Loop would then be ready once again to see if the analogue value holds above a certain point once more for 5 seconds and repeat

as such what approach should i take to check if an analogue value is equal to or above a certain amount for a certain time frame ( 5 seconds).

initially i considered something along the lines of (for test reasons said analogue value must be >= 50 for 5 seconds):

void setup() {
  // put your setup code here, to run once:
unsigned long startMillis;
int analogueValue;
boolean Switch = false;

void loop() {
  // put your main code here, to run repeatedly:

unsigned long currentMillis = millis();
if(analogueValue >= 50) startmillis = currentMillis;

if (currentMillis - startMillis <= 5000} Switch = true;

if (Switch = true)
//does something here
Switch = false;

but this approach doesn't work for obvious reasons, as when analogue value is more than or equal to 50 it constantly updates the start time. As such i have the wrong approach. What approach should i be adopting?

Check your spelling for a start.

I can definitely do that, but any ideas on a new approach to my problem?

You reversed the tests. Reset startmillis whenever the analogValue does not match the expectations. Set Switch if the elapsed time is >= the interval.

haven't implemented it yet, but the logic is sound, thanks for that can't believe it eluded me for that long.


This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.