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!

dda
1,5951 gold badge12 silver badges17 bronze badges
asked Feb 9, 2017 at 2:59
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? Commented 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. Commented 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);
 }
 ...
answered Feb 9, 2017 at 3:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.