Push buttons are an essential way to interact with the Arduino/RFzero. They are relatively simple to use provided they don’t bounce too much. However, debouncing can be made in both S/W and H/W. Below are two examples of how to do debounce in S/W, and how to detect a push button being pushed using an interrupt or scanning solution.
Interrupt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// RFzero include and object creation #include <RFzero.h> // MUST ALWAYS be included for RFzero #define pinPB A2 // Push button on pin A2 int debounceDelay = 10; // May be replaced by a larger value for heavy bouncing buttons void PushButton() { int timeStamp = millis(); static int lastTimeStamp = 0; if (timeStamp - lastTimeStamp > debounceDelay) SerialUSB.println("Push button pressed"); lastTimeStamp = timeStamp; } void setup() { // USB port setup SerialUSB.begin(9600); delay(2000); SerialUSB.println("Push button ready"); // Setup pin for push button pinMode(pinPB, INPUT); digitalWrite(pinPB, HIGH); // Setup interrupt handling for push button attachInterrupt(digitalPinToInterrupt(pinPB), PushButton, LOW); } void loop() {} |
Scanning
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// RFzero include and object creation #include <RFzero.h> // MUST ALWAYS be included for RFzero #define pinPB A2 // Push button on pin A2 int debounceDelay = 10; // May be replaced by a larger value for heavy bouncing buttons void PushButton() { int timeStamp = millis(); static int lastTimeStamp = 0; if ((digitalRead(pinPB) == LOW) && (timeStamp - lastTimeStamp > debounceDelay)) SerialUSB.println("Push button pressed"); lastTimeStamp = timeStamp; } void setup() { // USB port setup SerialUSB.begin(9600); delay(2000); SerialUSB.println("Push button ready"); // Setup pin for push button pinMode(pinPB, INPUT); digitalWrite(pinPB, HIGH); } void loop() { PushButton(); } |