0

I am very new to Arduino and I have this little bit of code:

if (R2 <= 200){
  counter=counter+1;
  Serial.print("counter: ");
  Serial.println(counter);
}

I want it to count every time R2 is less than or equal to 200, but I only want it to count once. Right now it adds to the counter 3-2 times while R2 is less than 200. I'd like it to only count once while in that range before R2 becomes greater than 200.

Any suggestions or links to helpful information would be very appreciated. Thank you!

2
  • Your question doesn't make sense. I want it to count every time R2 is less than or equal to 200, - OK "every time" you want to count. but I only want it to count once - so not every time?
    – Nick Gammon
    Feb 9, 2017 at 6:06
  • Do you mean: I want to add one to a counter if R2 is <= 200, but only once. Then if R2 is > 200 then I want to reset this process and do it again.
    – Nick Gammon
    Feb 9, 2017 at 6:08

1 Answer 1

1

You can set a flag to indicate that R2 is or has been above 200 since it last was low, much as follows.

// before loop() ...
byte Rhi = true;  // at outset, say that R2 has been high
...

// in loop() ...
  if (R2 > 200)          // Has R2 gone high?
    Rhi = true;
  if (Rhi && R2 <= 200){ // Has R2 gone low from high?
    Rhi = false;
    ++counter;
    Serial.print("counter: ");
    Serial.println(counter);
  }
  ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.