Sensing an "Event"

  • A lot of times when programming behaviour, we do not want repeat trigger when a button is pressed
  • This tutorial focus on how to sense an "Event" of keypress/keyrelease, the same logic can be applied to software "Schmitt Trigger" of analog input

Pre-requisite:

  1. Successfully Add a button

Objectives:

  1. To sense an "Event"
  2. The key is to detect "Change" in the system
  3. Try this code:

    const int buttonPin = 3;	// assuming using pin 3
    
    
    int buttonLast = HIGH;	// assuming low trigger (as default of many IR sensors and INPUT_PULLUP)
    void setup(){
    	Serial.begin(115200);
    	pinMode( buttonPin, INPUT );
    }
    
    
    void loop(){
    	int buttonNow = digitalRead(buttonPin);
    	if( buttonNow != buttonLast ){	// Changed
    		if( buttonNow == LOW ){
    			Serial.println("keypressed!");
    		}
    		if( buttonNow == HIGH ){
    			Serial.println("keyreleased");
    		}
    		// Don't forget to remember the value
    		buttonLast = buttonNow;
    	}
    }

    Note that each time you press or releases the button, the "keypressed" and "keyreleased" only shows only once.

  4. Or does it?
    1. Depending on the quality of the component and connection or electromagnetic field of the environment
      1. With good quality component/connection. the answer is YES
      2. However this is rare, usually we have imperfect mechanical connection and background noise in the environment that's affecting the wire( especially when the project contains motor )
        1. What we need to do in the case is called "Debouncing"
        2. There are many ways to do it, I'll put an example here:
        3. The idea is not to sense further event in certain time window.

          const int buttonPin = 3;	// assuming using pin 3
          unsigned long bounce_timestamp;
          
          int buttonLast = HIGH;	// assuming low trigger (as default of many IR sensors and INPUT_PULLUP)
          void setup(){
          	Serial.begin(115200);
          	pinMode( buttonPin, INPUT );
          	bounce_timestamp = millis();
          }
          
          
          void loop(){
          	int buttonNow = digitalRead(buttonPin);
          	if( buttonNow != buttonLast ){	// Changed
          		if( millis() - bounce_timestamp >=30 ){
          			bounce_timestamp = millis();	// only sense change after a 30ms window.
          			if( buttonNow == LOW ){
          				Serial.println("keypressed!");
          			}
          			if( buttonNow == HIGH ){
          				Serial.println("keyreleased");
          			}
          			// Don't forget to remember the value
          			buttonLast = buttonNow;
          		}
          	}
          }


  • No labels