/* Detecting changes This sample code shows the general structure by which you can detect changes in a signal, e.g. from LOW to HIGH or vice versa. In this example, we will turn on an LED whenever a signal on the SENSEPIN goes from LOW to HIGH (i.e. when a "rising" signal is detected). We will turn the LED off when SENSEPIN goes from HIGH to LOW (which is called a "falling" signal). The LED won't change if the input doesn't change. This document released to the public domain by the author in 2022 Robert Zacharias, rzachari@andrew.cmu.edu */ // pin assignments const int SENSEPIN = 7, // could be any sensor with HIGH/LOW digital output LEDPIN = 9; // simple LED output // input sensing variables int currentState, // the "new" reading each loop prevState; // the "old" reading from the prior loop // internal state variable bool LEDstate = true; // note: true == HIGH and false == LOW void setup() { pinMode(SENSEPIN, INPUT); pinMode(LEDPIN, OUTPUT); } void loop() { // 1. detect current state currentState = digitalRead(SENSEPIN); // 2a. check for rising state: was LOW, then just went HIGH // (note that an if() can be written without brackets needed // if the thing to do if it's true is just a single line) if (prevState == LOW && currentState == HIGH) LEDstate = true; // 2b. check for falling state: was HIGH, then just went LOW if (prevState == HIGH && currentState == LOW) LEDstate = false; // 3. drive output LED as appropriate digitalWrite (LEDPIN, LEDstate); // 4. store the current state into the previous state so that the // history is correctly saved for the next loop() previousState = currentState; }