Edge Detection

Most of the time, you don’t need to know whether a switch is on or off so much as you need to know when it changed. You want to know when it turned on or when it turned off. In other words, you want to find the edge of the transition from on to off, or vice versa. This is often called edge detection.

The basic idea is that you check not only what the state of the switch is, but what the state was the last time you checked, and compare the two. Here’s an example in PicBasic Pro:

switchStateVar var byte
lastSwitchStateVar var byte
switchCountVar var byte
input portd.1        ‘ the switch is on RD1
switchStateVar = 0

main:
    switchStateVar = portd.1
    ' if the switch isn't the same as it was last time through
    ' the main loop, then you want to do something:

    if switchStateVar <> lastswitchStateVar then    
        if switchStateVar = 1 then
            ' the switch went from off to on
            switchCountVar = switchCountVar + 1
            serout2 portc.6, 16468, ["switch is pressed.", 10, 13]
        else
            ' the switch went from on to off
            serout2 portc.6, 16468, ["switch is not pressed", 10, 13]
                            serout2 portc.6, 16468, [“switch hits: ", DEC switchCountVar, 10, 13]
        endif
            
                  ' store the state of the switch for next check:
        lastswitchStateVar = switchStateVar
    endif
goto main

Here it is in Arduino/Wiring

int switchPin = 2;
int switchCounterVar = 0;
int switchStateVar = 0;
int lastSwitchStateVar = 0;

void setup() {
  pinMode(switchPin, INPUT);
}


void loop() {
  // read the switch
  switchStateVar = digitalRead(switchPin);
  // compare the switch to its previous state
  if (switchStateVar != lastSwitchStateVar) {
    // if the state has changed, increment the counter
    if (switchStateVar == HIGH) {
      switchCounterVar++;
    }
    // save the current state as the last state, 
    //for next time through the loop
    lastSwitchStateVar = switchStateVar;
  }
}