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:
- Successfully Add a button
Objectives:
- To sense an "Event"
- The key is to detect "Change" in the system
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.
- Or does it?
- Depending on the quality of the component and connection or electromagnetic field of the environment
- With good quality component/connection. the answer is YES
- 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 )
- What we need to do in the case is called "Debouncing"
- There are many ways to do it, I'll put an example here:
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; } } }
- Depending on the quality of the component and connection or electromagnetic field of the environment