help with evaluating analogRead for a length of time

Status
Not open for further replies.

aperson

Member
Hey,
I was hoping someone would just tell me an easier(shorter) way to do this.

val = analog(0);
if(val < 0){
delay(1000)
a = 1
else
a = 0
if(val < 0 && a = 1)
delay(1000)
b = 1
else
b = 0
if(val < 0 && a = 1 && b = 1)
delay(1000)
c = 1
else
c = 0
if(val < 0 && a = 1 && b = 1 && c = 1)
delay(1000)
d = 1
else
d = 0

and so on....

Say you wanted to do something when analogRead was in a certain state for more than 60 seconds.

Thanks
 
I'd do something more like this (not tested):

Code:
void loop() {
  elapsedMillis waiting;     // "waiting" starts at zero
  while (waiting < 60000) {
    if (analogRead(0) < 1000)
      return;
  }
  // do action
}
 
From your short description, I may be misinterpreting exactly what you're after. However, if I'm understanding correctly, here's one possible approach:

Assumptions:
- you want to sample the analog input value once per second
- when the analog input value remains stable for >60 seconds, "take action"
- when the analog input value changes, then start the 60 second timer over
- once the analog input value has remained stable for >60 seconds (& you've taken action), start the 60 second timer over & look for the next 60 seconds of stability

Notes:
- analogRead() will tend to have some noise variation, so you may need to allow values within some range (e.g. +/- 2) to be considered "stable" & not reset the countdown accumulator, else you may never reach your 60 seconds of stability


Code:
#define THRESHOLD_SECONDS 60
unsigned int countdown_accumulator = THRESHOLD_SECONDS;
int settled_sample;

void setup()
{
   settled_sample = analogRead(0);
}

void loop()
{
   unsigned long last_start_millis = millis();
   int current_sample = analogRead(0);

   // delay for 1 second
   while (millis() < (last_start_millis + 1000)) {};

   // see if the value remains unchanged
   if (current_sample == settled_sample)
   {
      // if steady & count has exceeded the threshold value
      if (--countdown_accumulator == 0)
      {
         take_action();

         // if you also want to start over & look for settling again at this point
         countdown_accumulator = THRESHOLD_SECONDS;
      }
   } else {
      // otherwise, start over & look for settling again
      countdown_accumulator = THRESHOLD_SECONDS;
      settled_sample = current_sample;
   }
}

Good luck & have fun !!

Mark J Culross
KD5RXT
 
Status
Not open for further replies.
Back
Top