first commit

This commit is contained in:
lewishe
2023-04-11 11:27:36 +08:00
commit daa54b6448
2146 changed files with 915567 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
@mainpage AceButton Library
This is the Doxygen documentation for the
<a href="https://github.com/bxparks/AceButton">AceButton Library</a>.
*/
#ifndef ACE_BUTTON_H
#define ACE_BUTTON_H
#include "ace_button/TimingStats.h"
#include "ace_button/ButtonConfig.h"
#include "ace_button/AdjustableButtonConfig.h"
#include "ace_button/AceButton.h"
// Version format: xxyyzz == "xx.yy.zz"; 10303 = 1.3.3
#define ACE_BUTTON_VERSION 10303
#endif
@@ -0,0 +1,12 @@
/*
* This file has moved to <ace_button/AdjustableButtonConfig.h> and is
* deprecated as of version 1.1. The <AceButton.h> header automatically includes
* <ace_button/AdjustableButtonConfig.h>. You can remove the line in your code
* that does:
*
* #include <AdjustableButtonConfig.h>
*
* You only need to do:
*
* #include <AceButton.h>
*/
+11
View File
@@ -0,0 +1,11 @@
/*
* This file has moved to <ace_button/ButtonConfig.h> and is deprecated as
* of version 1.1. The <AceButton.h> header automatically includes
* <ace_button/ButtonConfig.h>. You can remove the line in your code that does:
*
* #include <ButtonConfig.h>
*
* You only need to do:
*
* #include <AceButton.h>
*/
+372
View File
@@ -0,0 +1,372 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "TimingStats.h"
#include "AceButton.h"
namespace ace_button {
// Check that the Arduino constants HIGH and LOW are defined to be 1 and 0,
// respectively. Otherwise, this library won't work.
#if HIGH != 1
#error HIGH must be defined to be 1
#endif
#if LOW != 0
#error LOW must be defined to be 0
#endif
AceButton::AceButton(uint8_t pin, uint8_t defaultReleasedState, uint8_t id):
mButtonConfig(ButtonConfig::getSystemButtonConfig()) {
init(pin, defaultReleasedState, id);
}
AceButton::AceButton(ButtonConfig* buttonConfig):
mButtonConfig(buttonConfig) {
init(0, HIGH, 0);
}
void AceButton::init(uint8_t pin, uint8_t defaultReleasedState, uint8_t id) {
mPin = pin;
mId = id;
mFlags = 0;
mLastButtonState = kButtonStateUnknown;
mLastDebounceTime = 0;
mLastClickTime = 0;
setDefaultReleasedState(defaultReleasedState);
}
void AceButton::setDefaultReleasedState(uint8_t state) {
if (state == HIGH) {
mFlags |= kFlagDefaultReleasedState;
} else {
mFlags &= ~kFlagDefaultReleasedState;
}
}
uint8_t AceButton::getDefaultReleasedState() {
return (mFlags & kFlagDefaultReleasedState) ? HIGH : LOW;
}
// NOTE: It would be interesting to rewrite the check() method using a Finite
// State Machine.
void AceButton::check() {
// Get the micros.
uint16_t nowMicros = mButtonConfig->getClockMicros();
// Retrieve the current time just once and use that in the various checkXxx()
// functions below. This provides some robustness of the various timing
// algorithms even if any of the event handlers takes more time than the
// threshold time limits such as 'debounceDelay' or longPressDelay'.
uint16_t now = mButtonConfig->getClock();
uint8_t buttonState = mButtonConfig->readButton(mPin);
// debounce the button
if (checkDebounced(now, buttonState)) {
// check if the button was initialized (i.e. UNKNOWN state)
if (checkInitialized(buttonState)) {
checkEvent(now, buttonState);
}
}
TimingStats* stats = mButtonConfig->getTimingStats();
if (stats != nullptr) {
uint16_t elapsedMicros = mButtonConfig->getClockMicros() - nowMicros;
stats->update(elapsedMicros);
}
}
void AceButton::checkEvent(uint16_t now, uint8_t buttonState) {
// We need to remove orphaned clicks even if just Click is enabled. It is not
// sufficient to do this for just DoubleClick. That's because it's possible
// for a Clicked event to be generated, then 65.536 seconds later, the
// ButtonConfig could be changed to enable DoubleClick. (Such real-time change
// of ButtonConfig is not recommended, but is sometimes convenient.) If the
// orphaned click is not cleared, then the next Click would be errorneously
// considered to be a DoubleClick. Therefore, we must clear the orphaned click
// even if just the Clicked event is enabled.
//
// We also need to check of any postponed clicks that got generated when
// kFeatureSuppressClickBeforeDoubleClick was enabled.
if (mButtonConfig->isFeature(ButtonConfig::kFeatureClick) ||
mButtonConfig->isFeature(ButtonConfig::kFeatureDoubleClick)) {
checkPostponedClick(now);
checkOrphanedClick(now);
}
if (mButtonConfig->isFeature(ButtonConfig::kFeatureLongPress)) {
checkLongPress(now, buttonState);
}
if (mButtonConfig->isFeature(ButtonConfig::kFeatureRepeatPress)) {
checkRepeatPress(now, buttonState);
}
if (buttonState != getLastButtonState()) {
checkChanged(now, buttonState);
}
}
bool AceButton::checkDebounced(uint16_t now, uint8_t buttonState) {
if (isDebouncing()) {
// NOTE: This is a bit tricky. The elapsedTime will be valid even if the
// uint16_t representation of 'now' rolls over so that (now <
// mLastDebounceTime). This is true as long as the 'unsigned long'
// representation of 'now' is < (65536 + mLastDebounceTime). We need to cast
// this expression into an uint16_t before doing the '>=' comparison below
// for compatability with processors whose sizeof(int) == 4 instead of 2.
// For those processors, the expression (now - mLastDebounceTime >=
// getDebounceDelay()) won't work because the terms in the expression get
// promoted to an (int).
uint16_t elapsedTime = now - mLastDebounceTime;
bool isDebouncingTimeOver =
(elapsedTime >= mButtonConfig->getDebounceDelay());
if (isDebouncingTimeOver) {
clearDebouncing();
return true;
} else {
return false;
}
} else {
// Currently not in debouncing phase. Check for a button state change. This
// will also detect a transition from kButtonStateUnknown to HIGH or LOW.
if (buttonState == getLastButtonState()) {
// no change, return immediately
return true;
}
// button has changed so, enter debouncing phase
setDebouncing();
mLastDebounceTime = now;
return false;
}
}
bool AceButton::checkInitialized(uint16_t buttonState) {
if (mLastButtonState != kButtonStateUnknown) {
return true;
}
// If transitioning from the initial "unknown" button state, just set the last
// valid button state, but don't fire off the event handler. This handles the
// case where a momentary switch is pressed down, then the board is rebooted.
// When the board comes up, it should not fire off the event handler. This
// also handles the case of a 2-position switch set to the "pressed"
// position, and the board is rebooted.
mLastButtonState = buttonState;
return false;
}
void AceButton::checkLongPress(uint16_t now, uint8_t buttonState) {
if (buttonState == getDefaultReleasedState()) {
return;
}
if (isPressed() && !isLongPressed()) {
uint16_t elapsedTime = now - mLastPressTime;
if (elapsedTime >= mButtonConfig->getLongPressDelay()) {
setLongPressed();
handleEvent(kEventLongPressed);
}
}
}
void AceButton::checkRepeatPress(uint16_t now, uint8_t buttonState) {
if (buttonState == getDefaultReleasedState()) {
return;
}
if (isPressed()) {
if (isRepeatPressed()) {
uint16_t elapsedTime = now - mLastRepeatPressTime;
if (elapsedTime >= mButtonConfig->getRepeatPressInterval()) {
handleEvent(kEventRepeatPressed);
mLastRepeatPressTime = now;
}
} else {
uint16_t elapsedTime = now - mLastPressTime;
if (elapsedTime >= mButtonConfig->getRepeatPressDelay()) {
setRepeatPressed();
// Trigger the RepeatPressed immedidately, instead of waiting until the
// first getRepeatPressInterval() has passed.
handleEvent(kEventRepeatPressed);
mLastRepeatPressTime = now;
}
}
}
}
void AceButton::checkChanged(uint16_t now, uint8_t buttonState) {
mLastButtonState = buttonState;
checkPressed(now, buttonState);
checkReleased(now, buttonState);
}
void AceButton::checkPressed(uint16_t now, uint8_t buttonState) {
if (buttonState == getDefaultReleasedState()) {
return;
}
// button was pressed
mLastPressTime = now;
setPressed();
handleEvent(kEventPressed);
}
void AceButton::checkReleased(uint16_t now, uint8_t buttonState) {
if (buttonState != getDefaultReleasedState()) {
return;
}
// Check for click (before sending off the Released event).
// Make sure that we don't clearPressed() before calling this.
if (mButtonConfig->isFeature(ButtonConfig::kFeatureClick)
|| mButtonConfig->isFeature(ButtonConfig::kFeatureDoubleClick)) {
checkClicked(now);
}
// check if Released events are suppressed
bool suppress =
((isLongPressed() &&
mButtonConfig->
isFeature(ButtonConfig::kFeatureSuppressAfterLongPress)) ||
(isRepeatPressed() &&
mButtonConfig->
isFeature(ButtonConfig::kFeatureSuppressAfterRepeatPress)) ||
(isClicked() &&
mButtonConfig->isFeature(ButtonConfig::kFeatureSuppressAfterClick)) ||
(isDoubleClicked() &&
mButtonConfig->
isFeature(ButtonConfig::kFeatureSuppressAfterDoubleClick)));
// button was released
clearPressed();
clearDoubleClicked();
clearLongPressed();
clearRepeatPressed();
if (!suppress) {
handleEvent(kEventReleased);
}
}
void AceButton::checkClicked(uint16_t now) {
if (!isPressed()) {
// Not a Click unless the previous state was a Pressed state.
// This can happen if the chip was rebooted with the button Pressed. Upon
// Release, it shouldn't generated a click, even accidentally due to a
// spurious value in mLastPressTime.
clearClicked();
return;
}
uint16_t elapsedTime = now - mLastPressTime;
if (elapsedTime >= mButtonConfig->getClickDelay()) {
clearClicked();
return;
}
// check for double click
if (mButtonConfig->isFeature(ButtonConfig::kFeatureDoubleClick)) {
checkDoubleClicked(now);
}
// Suppress a second click (both buttonState change and event message) if
// double-click detected, which has the side-effect of preventing 3 clicks
// from generating another double-click at the third click.
if (isDoubleClicked()) {
clearClicked();
return;
}
// we got a single click
mLastClickTime = now;
setClicked();
if (mButtonConfig->isFeature(
ButtonConfig::kFeatureSuppressClickBeforeDoubleClick)) {
setClickPostponed();
} else {
handleEvent(kEventClicked);
}
}
void AceButton::checkDoubleClicked(uint16_t now) {
if (!isClicked()) {
clearDoubleClicked();
return;
}
uint16_t elapsedTime = now - mLastClickTime;
if (elapsedTime >= mButtonConfig->getDoubleClickDelay()) {
clearDoubleClicked();
// There should be no postponed Click at this point because
// checkPostponedClick() should have taken care of it.
return;
}
// If there was a postponed click, suppress it because it could only have been
// postponed if kFeatureSuppressClickBeforeDoubleClick was enabled. If we got
// to this point, there was a DoubleClick, so we must suppress the first
// Click as requested.
if (isClickPostponed()) {
clearClickPostponed();
}
setDoubleClicked();
handleEvent(kEventDoubleClicked);
}
void AceButton::checkOrphanedClick(uint16_t now) {
// The amount of time which must pass before a click is determined to be
// orphaned and reclaimed. If only DoubleClicked is supported, then I think
// just getDoubleClickDelay() is correct. No other higher level event uses the
// first Clicked event. If TripleClicked becomes supported, I think
// orphanedClickDelay will be either (2 * getDoubleClickDelay()) or
// (getDoubleClickDelay() + getTripleClickDelay()), depending on whether the
// TripleClick has an independent delay time, or reuses the DoubleClick delay
// time. But I'm not sure that I've thought through all the details.
uint16_t orphanedClickDelay = mButtonConfig->getDoubleClickDelay();
uint16_t elapsedTime = now - mLastClickTime;
if (isClicked() && (elapsedTime >= orphanedClickDelay)) {
clearClicked();
}
}
void AceButton::checkPostponedClick(uint16_t now) {
uint16_t postponedClickDelay = mButtonConfig->getDoubleClickDelay();
uint16_t elapsedTime = now - mLastClickTime;
if (isClickPostponed() && elapsedTime >= postponedClickDelay) {
handleEvent(kEventClicked);
clearClickPostponed();
}
}
void AceButton::handleEvent(uint8_t eventType) {
ButtonConfig::EventHandler eventHandler = mButtonConfig->getEventHandler();
if (eventHandler) {
eventHandler(this, eventType, getLastButtonState());
}
}
}
+507
View File
@@ -0,0 +1,507 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_BUTTON_ACE_BUTTON_H
#define ACE_BUTTON_ACE_BUTTON_H
#if !defined(RASPBERRY_PI)
#include <Arduino.h>
#else
#include <raspi/raspi.h>
#endif /* RASPBERRY_PI */
#include "ButtonConfig.h"
namespace ace_button {
/**
* An Adjustable Compact Event-driven (ACE) Button library that debounces and
* dispatches button events to a user-defined event handler. Supported events
* types are:
*
* - kEventPressed
* - kEventReleased
* - kEventClicked
* - kEventDoubleClicked
* - kEventLongPressed
* - kEventRepeatPressed
*
* The check() method should be called from the loop() at least 2-3 times during
* the debouncing time period. For 20 ms delay, the check() method should be
* called at a minimum of every 5 ms. The execution time of check() on a 16
* MHz Arduino ATmega328P MCU seems to about about 12-14 microseconds.
*/
class AceButton {
public:
// The supported event types.
/** Button was pressed. */
static const uint8_t kEventPressed = 0;
/** Button was released. */
static const uint8_t kEventReleased = 1;
/**
* Button was clicked (Pressed and Released within
* ButtonConfig::getClickDelay()).
*/
static const uint8_t kEventClicked = 2;
/**
* Button was double-clicked. (Two clicks within
* ButtonConfig::getDoubleClickDelay()).
*/
static const uint8_t kEventDoubleClicked = 3;
/**
* Button was held down for longer than
* ButtonConfig::getLongPressDelay()).
*/
static const uint8_t kEventLongPressed = 4;
/**
* Button was held down and auto generated multiple presses. The first event
* is triggered after ButtonConfig::getRepeatPressDelay(), then the event
* fires repeatedly every ButtonConfig::getRepeatPressInterval() until the
* button is released.
*/
static const uint8_t kEventRepeatPressed = 5;
/**
* Button state is unknown. This is a third state (different from LOW or
* HIGH) used when the class is first initialized upon reboot.
*/
static const uint8_t kButtonStateUnknown = 2;
/**
* Constructor defines parameters of the button that changes from button to
* button. These parameters don't change during the runtime of the program.
* Another way to initialize the object is to create an instance using
* an empty constructor, then use the init() method to initialize the
* object with these parameters.
*
* Using the constructor often reads better for simple situations where only
* a single button is used, and it doesn't need to be configured
* significantly. Using the init() method can make the code be more readable
* when multiple buttons are used, and they need to be significantly
* customized. The init() method allows the button configuration code to
* appear in close proximity to the pinMode() methods which sets up the
* hardware pins.
*
* @param pin The pin number of the button. Default 0. Normally the pin
* number should be given at construction time. However, the pin number
* the pin number can be omitted so that the pin number can be assigned at
* setup() time using the setPin() method.
*
* @param defaultReleasedState The pin state when the button is in the
* initial released position. Default HIGH. When using a pullup resistor
* (either external or internal) and the button is connected to ground, this
* should be set to HIGH. When using an external pulldown resistor and the
* button is connected to Vcc (5V or 3.3V), this should be set to LOW. The
* defaultReleasedState can be assigned using the constructor or the
* init() method.
*
* @param id This is an optional user-defined identifier for the
* button. For example, this could be an index into an array of data that is
* associated with the button.
*/
explicit AceButton(uint8_t pin = 0, uint8_t defaultReleasedState = HIGH,
uint8_t id = 0);
/**
* Constructor that accepts a ButtonConfig as a dependency. Dependency
* injection using this constructor is now recommended over using the
* setButtonConfig() method because it makes the dependency more clear.
*/
explicit AceButton(ButtonConfig* buttonConfig);
/**
* Reset the button to the initial constructed state. In particular,
* getLastButtonState() returns kButtonStateUnknown. The parameters are
* identical as the parameters in the AceButton() constructor.
*/
void init(uint8_t pin = 0, uint8_t defaultReleasedState = HIGH,
uint8_t id = 0);
/** Get the ButtonConfig associated with this Button. */
ButtonConfig* getButtonConfig() ACE_BUTTON_INLINE {
return mButtonConfig;
}
/**
* Set the ButtonConfig associated with this Button. It is recommended that
* the AceButton(ButtonConfig*) constructor is used instead to make the
* dependency to ButtonConfig more explicit.
*/
void setButtonConfig(ButtonConfig* buttonConfig) ACE_BUTTON_INLINE {
mButtonConfig = buttonConfig;
}
/**
* Convenience method to set the event handler. Event handlers are stored in
* the ButtonConfig object, not in the AceButton object, to save
* memory. (Multiple buttons are likely to share the same event handler.) So
* this method is just a pass-through to ButtonConfig::setEventHandler(). If
* you are using multiple ButtonConfig objects, you should call the
* ButtonConfig::setEventHandler() method on those objects directly, instead
* of using this method.
*/
void setEventHandler(ButtonConfig::EventHandler eventHandler)
ACE_BUTTON_INLINE {
mButtonConfig->setEventHandler(eventHandler);
}
/** Get the button's pin number. */
uint8_t getPin() ACE_BUTTON_INLINE { return mPin; }
/** Get the custom identifier of the button. */
uint8_t getId() ACE_BUTTON_INLINE { return mId; }
/** Get the initial released state of the button, HIGH or LOW. */
uint8_t getDefaultReleasedState();
/**
* Return the button state that was last valid. This is a tri-state
* function. It may return HIGH, LOW or kButtonStateUnknown to indicate that
* the last state is not known. This method is **not** for public
* consumption, it is exposed only for testing purposes. Consider it to be a
* private method. Use the buttonState parameter provided to the
* EventHandler.
*
* In a more general multi-threaded environment (which the Arduino is not,
* fortunately or unfortunately), the getLastButtonState() may have changed
* from the value of buttonState provided to the event handler. In other
* words, there is a race-condition.
*/
uint8_t getLastButtonState() ACE_BUTTON_INLINE {
return mLastButtonState;
}
/**
* Check state of button and trigger event processing. This method should be
* called from the loop() method in Arduino every 4-5 times during the
* getDebounceDelay() time (default 20 ms), so about every 5 ms. If this
* is called less often than that, the debouncing algorithm may not work
* correctly, which may cause other event detection algorithms to fail.
*/
void check();
/**
* Returns true if the given buttonState represents a 'Released' state for
* the button. Returns false if the buttonState is 'Pressed' or
* kButtonStateUnknown.
*
* The HIGH or LOW logical value of buttonState represents different a
* button position depending on whether the button is wired with a pull-up
* or a pull-down resistor. This method translates the logical level to the
* physical position which allows the client code to be independent of the
* physical wiring.
*
* Normally, the eventType given to the EventHandler should be sufficient
* because the value of the eventType already encodes this information.
* This method is provided just in case.
*/
bool isReleased(uint8_t buttonState) ACE_BUTTON_INLINE {
return buttonState == getDefaultReleasedState();
}
/**
* Read the button state directly using ButtonConfig and return true if the
* button is in the Pressed state. This method is intended to be used in the
* global setup() to determine if the button was pressed while the device
* was booted. This method does not use the check() method, does not perform
* any debouncing, and does not dispatch events to the EventHandler.
*/
bool isPressedRaw() ACE_BUTTON_INLINE {
return !isReleased(mButtonConfig->readButton(mPin));
}
// Some of these private methods may be useful to the calling client but I
// don't want to release them to the public because I want to keep the API as
// small as possible for easier long term maintenance. (Once a method is
// released to the public, it must be supported forever to ensure backwards
// compatibility with older client code.)
private:
// Disable copy-constructor and assignment operator
AceButton(const AceButton&) = delete;
AceButton& operator=(const AceButton&) = delete;
/** Set the pin number of the button. */
void setPin(uint8_t pin) ACE_BUTTON_INLINE { mPin = pin; }
/**
* Set the initial released state of the button.
*
* @param state If a pull up resistor is used, this should be HIGH. If a
* pull down resistor is used, this should be LOW. The behavior is undefined
* for any other values of 'state'.
*/
void setDefaultReleasedState(uint8_t state);
/** Set the identifier of the button. */
void setId(uint8_t id) ACE_BUTTON_INLINE { mId = id; }
// Various bit masks to store a boolean flag in the 'mFlags' field.
// We use bit masks to save static RAM. If we had used a 'bool' type, each
// of these would consume one byte.
static const uint8_t kFlagDefaultReleasedState = 0x01;
static const uint8_t kFlagDebouncing = 0x02;
static const uint8_t kFlagPressed = 0x04;
static const uint8_t kFlagClicked = 0x08;
static const uint8_t kFlagDoubleClicked = 0x10;
static const uint8_t kFlagLongPressed = 0x20;
static const uint8_t kFlagRepeatPressed = 0x40;
static const uint8_t kFlagClickPostponed = 0x80;
// Methods for accessing the button's internal states.
// I don't expect these to be useful to the outside world.
// If this is set, then mLastDebounceTime is valid.
bool isDebouncing() ACE_BUTTON_INLINE {
return mFlags & kFlagDebouncing;
}
void setDebouncing() ACE_BUTTON_INLINE {
mFlags |= kFlagDebouncing;
}
void clearDebouncing() ACE_BUTTON_INLINE {
mFlags &= ~kFlagDebouncing;
}
// If this is set, then mLastPressTime is valid.
bool isPressed() ACE_BUTTON_INLINE {
return mFlags & kFlagPressed;
}
void setPressed() ACE_BUTTON_INLINE {
mFlags |= kFlagPressed;
}
void clearPressed() ACE_BUTTON_INLINE {
mFlags &= ~kFlagPressed;
}
// If this is set, then mLastClickTime is valid.
bool isClicked() ACE_BUTTON_INLINE {
return mFlags & kFlagClicked;
}
void setClicked() ACE_BUTTON_INLINE {
mFlags |= kFlagClicked;
}
void clearClicked() ACE_BUTTON_INLINE {
mFlags &= ~kFlagClicked;
}
// A double click was detected. No need to store the last double-clicked
// time because we don't support a triple-click event (yet).
bool isDoubleClicked() ACE_BUTTON_INLINE {
return mFlags & kFlagDoubleClicked;
}
void setDoubleClicked() ACE_BUTTON_INLINE {
mFlags |= kFlagDoubleClicked;
}
void clearDoubleClicked() ACE_BUTTON_INLINE {
mFlags &= ~kFlagDoubleClicked;
}
// If this is set, then mLastPressTime can be treated as the start
// of a long press.
bool isLongPressed() ACE_BUTTON_INLINE {
return mFlags & kFlagLongPressed;
}
void setLongPressed() ACE_BUTTON_INLINE {
mFlags |= kFlagLongPressed;
}
void clearLongPressed() ACE_BUTTON_INLINE {
mFlags &= ~kFlagLongPressed;
}
// If this is set, then mLastRepeatPressTime is valid.
bool isRepeatPressed() ACE_BUTTON_INLINE {
return mFlags & kFlagRepeatPressed;
}
void setRepeatPressed() ACE_BUTTON_INLINE {
mFlags |= kFlagRepeatPressed;
}
void clearRepeatPressed() ACE_BUTTON_INLINE {
mFlags &= ~kFlagRepeatPressed;
}
bool isClickPostponed() ACE_BUTTON_INLINE {
return mFlags & kFlagClickPostponed;
}
void setClickPostponed() ACE_BUTTON_INLINE {
mFlags |= kFlagClickPostponed;
}
void clearClickPostponed() ACE_BUTTON_INLINE {
mFlags &= ~kFlagClickPostponed;
}
/**
* Return true if debouncing succeeded and the buttonState value can be
* used. Return false if buttonState should be ignored until debouncing
* phase is complete.
*/
bool checkDebounced(uint16_t now, uint8_t buttonState);
/**
* Return true if the button was already initialzed and determined to be in
* a HIGH or LOW state. Return false if the button was previously in
* kButtonStateUnknown state which implies that the event handler should
* NOT be fired.
*/
bool checkInitialized(uint16_t buttonState);
/** Categorize the button event. */
void checkEvent(uint16_t now, uint8_t buttonState);
/** Check for a long press event and dispatch to event handler. */
void checkLongPress(uint16_t now, uint8_t buttonState);
/** Check for a repeat press event and dispatch to event handler. */
void checkRepeatPress(uint16_t now, uint8_t buttonState);
/** Check for onChange event and check for Press or Release events. */
void checkChanged(uint16_t now, uint8_t buttonState);
/**
* Check for Released and Click events and dispatch to respective
* handlers.
*/
void checkReleased(uint16_t now, uint8_t buttonState);
/** Check for Pressed event and dispatch to handler. */
void checkPressed(uint16_t now, uint8_t buttonState);
/** Check for a single click event and dispatch to handler. */
void checkClicked(uint16_t now);
/**
* Check for a double click event and dispatch to handler. Return true if
* double click detected.
*/
void checkDoubleClicked(uint16_t now);
/**
* Check for an orphaned click that did not generate a double click and
* clean up internal state. If we don't do this, the second click may be
* generated after the uint16_t rolls over in 65.5 seconds, causing an
* unwanted double-click. Even if we used the full 'unsigned long' to store
* the 'lastClickTime', we'd still need this function to prevent a rollover
* of the 32-bit number in 49.7 days.
*/
void checkOrphanedClick(uint16_t now);
/**
* Check if a click message has been postponed because of
* ButtonConfig::kFeatureSuppressClickBeforeDoubleClick.
*/
void checkPostponedClick(uint16_t now);
/**
* Dispatch to the event handler defined in the mButtonConfig.
*
* This method will always be called and it's up to the user-provided
* handler to ignore the events which aren't interesting.
*
* An alternative might be to provide a bitmask filter to select only
* events which should are registered to trigger the event handler. For
* example, add the following method:
*
* @code
* setEventSelection(uint8_t eventSelection) {
* mEventSelection = eventSelection;
* }
* @endcode
*
* Set the event selector at setup():
*
* @code
* setEventSelection(kEventSelectPressed | kEventSelectReleased);
* @endcode
*
* where
*
* @code
* kEventSelectPressed = (0x1 << kEventPressed);
* kEventSelectReleased = (0x1 << kEventReleased);
* ...
* @endcode
*
* Then change the handleEvent() method to something like:
*
* @code
* void handleEvent(uint8_t eventType) {
* if (mEventHandler && (eventSelections & (0x1 << eventType))) {
* handleEvent(this, eventType);
* }
* }
* @endcode
*
* But it is possible that the evaluation of the if-condition above takes
* longer to evaluate than an empty function call, so we should do some
* profiling before making this change.
*
* @param eventType the type of event given by the kEvent* constants
*/
void handleEvent(uint8_t eventType);
uint8_t mPin; // button pin number
uint8_t mId; // identifier, e.g. an index into an array
// Internal states of the button debouncing and event handling.
// NOTE: We don't keep track of the lastDoubleClickTime, because we
// don't support a TripleClicked event. That may change in the future.
uint16_t mLastDebounceTime; // ms
uint16_t mLastClickTime; // ms
uint16_t mLastPressTime; // ms
uint16_t mLastRepeatPressTime; // ms
/** Internal flags. Bit masks are defined by the kFlag* constants. */
uint8_t mFlags;
/**
* Last button state. This is a tri-state variable: LOW, HIGH or
* kButtonStateUnknown.
*/
uint8_t mLastButtonState;
/** ButtonConfig associated with this button. */
ButtonConfig* mButtonConfig;
};
}
#endif
@@ -0,0 +1,47 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_BUTTON_ADJUSTABLE_BUTTON_CONFIG_H
#define ACE_BUTTON_ADJUSTABLE_BUTTON_CONFIG_H
#include "ButtonConfig.h"
namespace ace_button {
/**
* A subclass of ButtonConfig which allows the user to override the varous
* timing parameters of ButtonConfig at runtime. Each timing parameter
* is stored in a member variable, so an instance of AdjustableButtonConfig
* consumes far more static RAM than ButtonConfig. In return, this class allows
* these parameters to be changed at runtime by the user.
*
* Warning: This class is deprecated and replaced with its parent ButtonConfig
* class. You can just use ButtonConfig everywhere you previously used
* AdjustableButtonConfig.
*/
class AdjustableButtonConfig: public ButtonConfig {
};
}
#endif
@@ -0,0 +1,32 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "ButtonConfig.h"
namespace ace_button {
// The default "System" instance of a ButtonConfig.
ButtonConfig ButtonConfig::sSystemButtonConfig;
}
+361
View File
@@ -0,0 +1,361 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_BUTTON_BUTTON_CONFIG_H
#define ACE_BUTTON_BUTTON_CONFIG_H
#if !defined(RASPBERRY_PI)
#include <Arduino.h>
#else
#include <raspi/raspi.h>
#endif /* RASPBERRY_PI */
// TODO: Verify if this is actually needed. The program size seems to be
// identical with or without it on the Arduino IDE (which uses gcc).
#define ACE_BUTTON_INLINE __attribute__((always_inline))
namespace ace_button {
class AceButton;
class TimingStats;
/**
* Class that defines the timing parameters and event handler of an AceButton or
* a group of AceButton instances. It is assumed that in many cases, a group of
* multiple buttons will need to be assigned the same configuration parameters.
* For example, various timing delays and the EventHandler. Instead of storing
* these parameters in each instance of AceButton (which consumes static
* memory), we save space by collecting them into a separate ButtonConfig class.
* Each AceButton instance contains a pointer to an instance of ButtonConfig,
* and an instance of ButtonConfig will be shared among multiple AceButtons.
*
* Various timing parameters are given default values. They can be
* overridden by the user.
*
* A single default "System" ButtonConfig instance is created automatically and
* can be accessed using the ButtConfig::getSystemButtonConfig() static method.
* For convenience and ease of use, every instance of AceButton is attached to
* this "System" ButtonConfig by default. The client code can override this
* association by attaching another ButtonConfig instance using the
* AceButton(ButtonConfig*) constuctor (the recommended solution) or the
* AceButton::setButtonConfig() method.
*/
class ButtonConfig {
public:
// Various timing constants, in milliseconds.
//
// Note that the timing constants are stored as uint16_t (2
// bytes) instead of unsigned long (4 bytes) which is the type returned by
// the millis() system method. It turns out that we can store and perform
// all timing calculations using uint16_t without ill effect, as long as the
// polling of AceButton::check() happens more frequently than the rollover
// time of a uint16_t (i.e. 65.536 seconds) and certain precautions (e.g.
// AceButton::checkOrphanedClick()) are taken before a uint16_t rollover
// happens. In theory, these additional precautions would be needed even if
// an 'unsigned long' is used but almost no one does them because they
// assume that their code won't be running continuously for the rollover
// time of an 'unsigned long' (i.e. 49.7 days).
/** Default value returned by getDebounceDelay(). */
static const uint16_t kDebounceDelay = 20;
/** Default value returned by getClickDelay(). */
static const uint16_t kClickDelay = 200;
/** Default value returned by getDoubleClickDelay(). */
static const uint16_t kDoubleClickDelay = 400;
/** Default value returned by getLongPressDelay(). */
static const uint16_t kLongPressDelay = 1000;
/** Default value returned by getRepeatPressDelay(). */
static const uint16_t kRepeatPressDelay = 1000;
/** Default value returned by getRepeatPressInterval(). */
static const uint16_t kRepeatPressInterval = 200;
// Various features controlled by feature flags.
/**
* Type of the feature flag. It used to be a uint8_t but got changed to a
* uint16_t when more than 8 flags were needed. Let's define a typedef to
* make it easier to change this in the future.
*/
typedef uint16_t FeatureFlagType;
/** Flag to activate the AceButton::kEventClicked event. */
static const FeatureFlagType kFeatureClick = 0x01;
/**
* Flag to activate the AceButton::kEventDoubleClicked event.
* Activating this automatically activates kEventClicked since there is
* no double-click without a click.
*/
static const FeatureFlagType kFeatureDoubleClick = 0x02;
/** Flag to activate the AceButton::kEventLongPress event. */
static const FeatureFlagType kFeatureLongPress = 0x04;
/** Flag to activate the AceButton::kEventRepeatPressed event. */
static const FeatureFlagType kFeatureRepeatPress = 0x08;
/** Flag to suppress kEventReleased after a kEventClicked. */
static const FeatureFlagType kFeatureSuppressAfterClick = 0x10;
/**
* Flag to suppress kEventReleased after a kEventDoubleClicked. A
* kEventClicked is _always_ suppressed after a kEventDoubleClicked to
* prevent generating 2 double-clicks if the user performed a triple-click.
*/
static const FeatureFlagType kFeatureSuppressAfterDoubleClick = 0x20;
/** Flag to suppress kEventReleased after a kEventLongPressed. */
static const FeatureFlagType kFeatureSuppressAfterLongPress = 0x40;
/** Flag to suppress kEventReleased after a kEventRepeatPressed. */
static const FeatureFlagType kFeatureSuppressAfterRepeatPress = 0x80;
/**
* Flag to suppress kEventClicked before a kEventDoubleClicked. This causes
* the notification of a kEventClicked to be delayed until the delay time of
* getDoubleClickDelay() has passed so that we can determine if there was a
* kEventDoubleClicked.
*/
static const FeatureFlagType kFeatureSuppressClickBeforeDoubleClick = 0x100;
/**
* Convenience flag to suppress all suppressions. Calling
* setFeature(kFeatureSuppressAll) suppresses all and
* clearFeature(kFeatureSuppressAll) clears all suppression. Note however
* that isFeature(kFeatureSuppressAll) currently means "is ANY feature
* enabled?" not "are ALL features enabled?".
*/
static const FeatureFlagType kFeatureSuppressAll =
(kFeatureSuppressAfterClick |
kFeatureSuppressAfterDoubleClick |
kFeatureSuppressAfterLongPress |
kFeatureSuppressAfterRepeatPress |
kFeatureSuppressClickBeforeDoubleClick);
/**
* The event handler signature.
*
* @param button pointer to the AceButton that generated the event
* @param eventType the event type which trigger the call
* @param buttonState the state of the button that triggered the event
*/
typedef void (*EventHandler)(AceButton* button, uint8_t eventType,
uint8_t buttonState);
/** Constructor. */
ButtonConfig() {}
// These configuration methods are virtual so that they can be overriddden.
// Subclasses can override at the class-level by defining a new virtual
// function in the subclass, or by defining an instance variable and storing
// the parameter with each instance of this class.
/** Milliseconds to wait for debouncing. */
uint16_t getDebounceDelay() { return mDebounceDelay; }
/** Milliseconds to wait for a possible click. */
uint16_t getClickDelay() { return mClickDelay; }
/**
* Milliseconds between the first and second click to register as a
* double-click.
*/
uint16_t getDoubleClickDelay() {
return mDoubleClickDelay;
}
/** Milliseconds for a long press event. */
uint16_t getLongPressDelay() {
return mLongPressDelay;
}
/**
* Milliseconds that a button needs to be Pressed down before the start of
* the sequence of RepeatPressed events. The first event will fire as soon
* as this delay has passed. Subsequent events will fire after
* getRepeatPressInterval() time.
*/
uint16_t getRepeatPressDelay() {
return mRepeatPressDelay;
}
/**
* Milliseconds between two successive RepeatPressed events.
*/
uint16_t getRepeatPressInterval() {
return mRepeatPressInterval;
}
/** Set the debounceDelay. */
void setDebounceDelay(uint16_t debounceDelay) {
mDebounceDelay = debounceDelay;
}
/** Set the clickDelay. */
void setClickDelay(uint16_t clickDelay) {
mClickDelay = clickDelay;
}
/** Set the doubleClickDelay. */
void setDoubleClickDelay(uint16_t doubleClickDelay) {
mDoubleClickDelay = doubleClickDelay;
}
/** Set the longPressDelay. */
void setLongPressDelay(uint16_t longPressDelay) {
mLongPressDelay = longPressDelay;
}
/** Set the repeatPressDelay. */
void setRepeatPressDelay(uint16_t repeatPressDelay) {
mRepeatPressDelay = repeatPressDelay;
}
/** Set the repeatPressInterval. */
void setRepeatPressInterval(uint16_t repeatPressInterval) {
mRepeatPressInterval = repeatPressInterval;
}
// The getClock() and readButton() are external dependencies that normally
// would be injected using separate classes, but in the interest of saving
// RAM in an embedded environment, we expose them in this class instead.
/**
* Return the milliseconds of the internal clock. Override to use something
* other than millis(). The return type is 'unsigned long' instead of
* uint16_t because that's the return type of millis().
*/
virtual unsigned long getClock() { return millis(); }
/**
* Return the microseconds of the internal clock. Can be overridden
* for testing purposes.
*/
virtual unsigned long getClockMicros() { return micros(); }
/**
* Return the HIGH or LOW state of the button. Override to use something
* other than digitalRead(). The return type is 'int' instead of uint16_t
* because that's the return type of digitalRead().
*/
virtual int readButton(uint8_t pin) {
return digitalRead(pin);
}
// These methods return the various feature flags that control the
// functionality of the AceButton.
/** Check if the given features are enabled. */
bool isFeature(FeatureFlagType features) ACE_BUTTON_INLINE {
return mFeatureFlags & features;
}
/** Enable the given features. */
void setFeature(FeatureFlagType features) ACE_BUTTON_INLINE {
mFeatureFlags |= features;
}
/** Disable the given features. */
void clearFeature(FeatureFlagType features) ACE_BUTTON_INLINE {
mFeatureFlags &= ~features;
}
// EventHandler
/** Return the eventHandler. */
EventHandler getEventHandler() ACE_BUTTON_INLINE {
return mEventHandler;
}
/**
* Install the event handler. The event handler must be defined for the
* AceButton to be useful.
*/
void setEventHandler(EventHandler eventHandler) ACE_BUTTON_INLINE {
mEventHandler = eventHandler;
}
// TimingStats
/** Set the timing stats object. The timingStats can be nullptr. */
void setTimingStats(TimingStats* timingStats) {
mTimingStats = timingStats;
}
/** Get the timing stats. Can return nullptr. */
TimingStats* getTimingStats() { return mTimingStats; }
/**
* Return a pointer to the singleton instance of the ButtonConfig
* which is attached to all AceButton instances by default.
*/
static ButtonConfig* getSystemButtonConfig() ACE_BUTTON_INLINE {
return &sSystemButtonConfig;
}
protected:
/**
* Initialize to its pristine state, except for the EventHandler which is
* unchanged. This is intended mostly for testing purposes.
*/
virtual void init() {
mFeatureFlags = 0;
mTimingStats = nullptr;
}
private:
/**
* A single static instance of ButtonConfig provided by default to all
* AceButton instances.
*/
static ButtonConfig sSystemButtonConfig;
// Disable copy-constructor and assignment operator
ButtonConfig(const ButtonConfig&) = delete;
ButtonConfig& operator=(const ButtonConfig&) = delete;
/** The event handler for all buttons associated with this ButtonConfig. */
EventHandler mEventHandler = nullptr;
/** A bit mask flag that activates certain features. */
FeatureFlagType mFeatureFlags = 0;
/** The timing stats object. */
TimingStats* mTimingStats = nullptr;
uint16_t mDebounceDelay = kDebounceDelay;
uint16_t mClickDelay = kClickDelay;
uint16_t mDoubleClickDelay = kDoubleClickDelay;
uint16_t mLongPressDelay = kLongPressDelay;
uint16_t mRepeatPressDelay = kRepeatPressDelay;
uint16_t mRepeatPressInterval = kRepeatPressInterval;
};
}
#endif
@@ -0,0 +1,90 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_BUTTON_TIMING_STATS_H
#define ACE_BUTTON_TIMING_STATS_H
#include <stdint.h>
namespace ace_button {
class TimingStats {
public:
/** Constructor. Default copy-constructor and assignment operator ok. */
TimingStats(): mCounter(0) {
reset();
}
void reset() {
mExpDecayAvg = 0;
mMin = UINT16_MAX;
mMax = 0;
mSum = 0;
mCount = 0;
}
uint16_t getMax() const { return mMax; }
uint16_t getMin() const { return mMin; }
uint16_t getAvg() const { return (mCount > 0) ? mSum / mCount : 0; }
/** An exponential decay average. */
uint16_t getExpDecayAvg() const { return mExpDecayAvg; }
/** Number of times update() was called since last reset. */
uint16_t getCount() const { return mCount; }
/**
* Number of times update() was called from the beginning of time. Never
* reset. This is useful to determining how many times update() was called
* since it was last checked from the client code.
*/
uint16_t getCounter() const { return mCounter; }
void update(uint16_t duration) {
mCount++;
mCounter++;
mSum += duration;
if (duration < mMin) {
mMin = duration;
}
if (duration > mMax) {
mMax = duration;
}
mExpDecayAvg = (mExpDecayAvg + duration) / 2;
}
private:
uint16_t mExpDecayAvg;
uint16_t mMin;
uint16_t mMax;
uint32_t mSum;
uint16_t mCount;
uint16_t mCounter;
};
}
#endif
@@ -0,0 +1,99 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_BUTTON_EVENT_TRACKER_H
#define ACE_BUTTON_EVENT_TRACKER_H
namespace ace_button {
namespace testing {
/**
* A record of an AceButton event, for testing purposes.
*/
class EventRecord {
public:
EventRecord():
mEventType(0),
mButtonState(LOW) {}
EventRecord(uint8_t eventType, uint8_t buttonState):
mEventType(eventType),
mButtonState(buttonState) {}
uint8_t getEventType() {
return mEventType;
}
uint8_t getButtonState() {
return mButtonState;
}
private:
// Accept the default copy-constructor and assignment operator.
//EventRecord(const EventRecord&) = delete;
//EventRecord& operator=(const EventRecord&) = delete;
uint8_t mEventType;
uint8_t mButtonState;
};
/**
* Class that can receive and remember multiple calls to the eventHandler from
* AceButton.
*/
class EventTracker {
public:
EventTracker():
mNumEvents(0) {}
/** Add event to a buffer of records, stopping when the buffer fills up. */
void addEvent(uint8_t eventType, uint8_t buttonState) {
if (mNumEvents < kMaxEvents) {
mRecords[mNumEvents] = EventRecord(eventType, buttonState);
mNumEvents++;
}
}
void clear() { mNumEvents = 0; }
int getNumEvents() { return mNumEvents; }
EventRecord& getRecord(int i) { return mRecords[i]; }
private:
// Disable copy-constructor and assignment operator
EventTracker(const EventTracker&) = delete;
EventTracker& operator=(const EventTracker&) = delete;
// Don't expect more than about 3. Set to 5 just in case.
static const int kMaxEvents = 5;
EventRecord mRecords[kMaxEvents];
int mNumEvents;
};
}
}
#endif
@@ -0,0 +1,109 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_BUTTON_TEST_HELPER_H
#define ACE_BUTTON_TEST_HELPER_H
#include <AceButton.h>
#include "TestableButtonConfig.h"
#include "EventTracker.h"
namespace ace_button {
namespace testing {
/**
* A wrapper class that sends emulated button presses and released to the the
* underlying AceButton class, and captures the resulting events in the
* provided EventTracker.
*/
class TestHelper {
public:
TestHelper(
TestableButtonConfig* testableConfig,
AceButton* button,
EventTracker* eventTracker):
mTestableConfig(testableConfig),
mButton(button),
mEventTracker(eventTracker) {}
/** Reinitilize to its pristine state. */
void init(uint8_t pin, uint8_t defaultReleasedState, uint8_t id) {
mPin = pin;
mDefaultReleasedState = defaultReleasedState;
mId = id;
mButton->init(mPin, mDefaultReleasedState, mId);
mTestableConfig->init();
mTestableConfig->setButtonState(defaultReleasedState);
}
/**
* Simulate a press of the button and run the button.check() processing. The
* defaultReleasedState is determined by whether the button has a pullup
* (HIGH) or pulldown (LOW) resistor.
*/
void pressButton(unsigned long time) {
uint8_t targetState = (HIGH == mDefaultReleasedState) ? LOW : HIGH;
mTestableConfig->setClock(time);
mTestableConfig->setButtonState(targetState);
mEventTracker->clear();
mButton->check();
}
/**
* Simulate a release of the button and run the button.check() processing.
*/
void releaseButton(unsigned long time) {
uint8_t targetState = (HIGH == mDefaultReleasedState) ? HIGH : LOW;
mTestableConfig->setClock(time);
mTestableConfig->setButtonState(targetState);
mEventTracker->clear();
mButton->check();
}
/**
* Simply move the time forward and check the button. No changes to button.
*/
void checkTime(unsigned long time) {
mTestableConfig->setClock(time);
mEventTracker->clear();
mButton->check();
}
private:
// Disable copy-constructor and assignment operator
TestHelper(const TestHelper&) = delete;
TestHelper& operator=(const TestHelper&) = delete;
TestableButtonConfig* mTestableConfig;
AceButton* mButton;
EventTracker* mEventTracker;
uint8_t mPin;
uint8_t mDefaultReleasedState;
uint8_t mId;
};
}
}
#endif
@@ -0,0 +1,80 @@
/*
MIT License
Copyright (c) 2018 Brian T. Park
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef ACE_BUTTON_TESTABLE_BUTTON_CONFIG_H
#define ACE_BUTTON_TESTABLE_BUTTON_CONFIG_H
#include "../ButtonConfig.h"
namespace ace_button {
namespace testing {
/**
* A subclass of ButtonConfig which overrides getClock() and readButton() so
* that their values can be controlled manually. This is intended to be used for
* unit testing.
*/
class TestableButtonConfig: public ButtonConfig {
public:
TestableButtonConfig():
mMillis(0),
mButtonState(HIGH) {}
/**
* Initialize to its pristine state. This method is needed because
* ArduinoUnit does not create a new instance of the Test class for each
* test case, so we have to reuse objects between test cases, so we need a
* way to reinitialize this object to its pristine state just after
* construction.
*/
void init() override {
ButtonConfig::init();
mMillis = 0;
mButtonState = HIGH;
}
/** Read the time of the fake clock. */
unsigned long getClock() override { return mMillis; }
/** Read the fake physical button. */
int readButton(uint8_t /* pin */) override { return mButtonState; }
/** Set the time of the fake clock. */
void setClock(unsigned long millis) { mMillis = millis; }
/** Set the state of the fake physical button. */
void setButtonState(int buttonState) { mButtonState = buttonState; }
private:
// Disable copy-constructor and assignment operator
TestableButtonConfig(const TestableButtonConfig&) = delete;
TestableButtonConfig& operator=(const TestableButtonConfig&) = delete;
unsigned long mMillis;
int mButtonState;
};
}
}
#endif