Evaluate if a value is increasing or decreasing (arduino)

mishap_n picture mishap_n · Nov 14, 2013 · Viewed 10.9k times · Source

I'm trying to learn how to evaluate if a value is increasing or decreasing. In this case I'm using a potentiometer mapped from 0 - 14. Basically I need it to look at the current value, and if the current value is increasing print one thing, and if the value is decreasing print something else.

Here's what I have so far, I know its not right, but its a start.

Thoughts?

Thank you.

void setup() { 
  Serial.begin(9600);  
}


void loop() {

  int val = analogRead(A0);  // read the input on analog pin 0:
  val = map(val, 0, 1023, 0, 14); // map the vlaues to new values
  Serial.println(val); // print those values
  delay(1); // delay by a second.

  // sudo code

  if (val++) {

    Serial.println("up");

  } else if (val--){

    Serial.print("down");

  }else{

    // do nothing
  }
}// end loop

Answer

Desko27 picture Desko27 · Nov 15, 2013

Declaration of variables

int val = analogRead(A0);  // read the input on analog pin 0:

I don't recommend you to declare variables in the loop() function when you can declare them outside once:

// declaration here!
int val = 0;

void setup() { 
  Serial.begin(9600);  
}

void loop() {

  // just set the value
  val = analogRead(A0);  // read the input on analog pin 0:
  val = map(val, 0, 1023, 0, 14); // map the vlaues to new values

      ...

Increase / decrease checks

In C++ you can make an assignment even in a conditional statement. if (val++) and if (val--) won't do what you expect. The if statement checks if val is not false or 0, and then ++ increases it by 1. Same for val-- but decreasing by -1.

What you can do is to keep the previous value in another variable (let's say prev) to compare it later like this:

// declaration here!
int val = 0;
int prev;

    ...

void loop() {

    // keep the previous value
    prev = val;

    // just set the value
    val = analogRead(A0);  // read the input on analog pin 0:

    ...

    // compare the previous value
    if (val > prev) {
        Serial.println("up");
    } else if (val < prev) {
        Serial.println("down");
    }

    // and no need to leave empty an `else` block

}