Go Down

Topic: Plus or minus X (Read 5853 times) previous topic - next topic

AndyJarosz

Jun 12, 2011, 10:03 pm Last Edit: Jun 12, 2011, 10:06 pm by AndyJarosz Reason: 1
Is there any way to have the Arduino recognize when it is within, say plus or minus 10 of a number? For example, if a rotary encoder is within X either way of a certain number, it lights an LED?

Chicken325

This should light up the pin 13 LED if encoderVal and otherVal happen to be 10 or less away from each other:
Code: [Select]
void setup() {               
  pinMode(13, OUTPUT);   
  int encoderVal = random(-20, 20);
  int otherVal = random(-20, 20);
  if(abs(encoderVal - otherVal) <= 10) {
    digitalWrite(13, HIGH);
  } else {
    digitalWrite(13, LOW);
  }
}

void loop() {}

Untested.

udoklein

Also untested but shorter:
Code: [Select]

    digitalWrite(13, abs(encoderVal - otherVal) <= 10);
Check out my experiments http://blog.blinkenlight.net

AndyJarosz

Brilliant, thanks everyone!

Go Up