Added a Button class

This commit is contained in:
Thomas O Fredericks
2020-05-19 14:06:37 -04:00
parent cf32eda85e
commit 1af864b0bd
5 changed files with 114 additions and 1 deletions
+61
View File
@@ -0,0 +1,61 @@
/*
DESCRIPTION
====================
Simple example of the Button class from the Bounce library.
The Button class matches an electrical state to a physical action.
that switches the debug LED when
either of 2 buttons are pressed.
*/
// Include the Bounce2 library found here :
// https://github.com/thomasfredericks/Bounce2
#include <Bounce2.h>
#define BUTTON_PIN_A 2
#define BUTTON_PIN_B 3
#define LED_PIN 13
// Instantiate a Button object
Button buttonA = Button();
// Instantiate another Button object
Button buttonB = Button();
void setup() {
// SETUP BUTTON A
buttonA.attach( BUTTON_PIN_A , INPUT_PULLUP );
buttonA.interval(5); // interval in ms
buttonA.setPressedState(LOW); // INDICATE THAT THE LOW STATE CORRESPONDS TO PHYSICALLY PRESSING THE BUTTON
// SETUP BUTTON B
buttonB.attach( BUTTON_PIN_B , INPUT_PULLUP );
buttonB.interval(5); // interval in ms
buttonB.setPressedState(LOW); // INDICATE THAT THE LOW STATE CORRESPONDS TO PHYSICALLY PRESSING THE BUTTON
// SETUP LED
pinMode(LED_PIN,OUTPUT);
}
void loop() {
// UPDATE THE BUTTONS
buttonA.update();
buttonB.update();
// TURN ON LED IF EITHER BUTTON IS PRESSED
if ( buttonA.pressed() || buttonB.pressed() ) {
digitalWrite(LED_PIN, HIGH );
}
else {
digitalWrite(LED_PIN, LOW );
}
}
+5 -1
View File
@@ -7,7 +7,8 @@
#######################################
Bounce KEYWORD1
Bounce2 KEYWORD1
Bounce2 KEYWORD1
Button KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
@@ -20,6 +21,9 @@ attach KEYWORD2
rose KEYWORD2
fell KEYWORD2
duration KEYWORD2
pressed KEYWORD2
released KEYWORD2
setPressedState KEYWORD2
#######################################
# Instances (KEYWORD2)
+48
View File
@@ -208,6 +208,54 @@ class Bounce
public:
bool changed( ) { return getStateFlag(CHANGED_STATE); }
};
/**
The Button class.
*/
class Button : public Bounce{
protected:
bool stateForPressed = 0;
public:
/*!
@brief Create an instance of the Button class.
@code
// Create an instance of the Button class.
Button() button;
@endcode
*/
Button(){ }
/*!
@brief Set the electrical state (HIGH/LOW) that corresponds to a physical press.
@param state
The electrical state (HIGH/LOW) that corresponds to a physical press.
*/
void setPressedState(bool state){
stateForPressed = state;
}
/*!
@brief Returns true if the button was physically pressed
*/
bool pressed() {
return changed() && (read() == stateForPressed);
};
/*!
@brief Returns true if the button was physically released
*/
bool released() {
return changed() && (read() != stateForPressed);
};
};
#endif