Condition on variable change?

Hi, how could I write an if statement that triggers when the value of a variable changes? The value is being read from serial and might be a certain integer for a number of loops, then increment by 1. I want something to happen when that increase occurs.

Answers

    • Serial library already got a trigger called serialEvent().
    • Just declare some global boolean variable in order to flag the special event.
    • Inside serialEvent(), set the boolean flag to true.
    • Inside draw(), check whether the flag is true and execute the special action if so.
    • After the special action is done, unset the flag to false.
  • I think what you describe will work if I go back and change the Arduino code to only transmit to serial when a certain threshold on my sensor is reached (currently it constantly outputs a count of events). I'll give it a shot, thanks.

  • Otherwise you can record the last value seen in a global variable, and when it changes from that value, the event triggers.

    int glob;
    
    if ( val != glob ){
      glob = val;
      event();
    }
    
Sign In or Register to comment.