This commit is contained in:
Michal Courson
2025-08-28 21:39:35 -04:00
commit b1e155d08b
28 changed files with 7246 additions and 0 deletions

87
main/Switch.hpp Normal file
View File

@ -0,0 +1,87 @@
#ifndef SWITCH_HPP
#define SWITCH_HPP
#include <Arduino.h>
class Switch {
public:
/** Specifies the expected behavior of the switch */
enum Type {
TYPE_TOGGLE, /**< & */
TYPE_MOMENTARY, /**< & */
};
/** Specifies whether the pressed is HIGH or LOW. */
enum Polarity {
POLARITY_NORMAL, /**< & */
POLARITY_INVERTED, /**< & */
};
Switch() {}
~Switch() {}
/**
Initializes the switch object with a given port/pin combo.
\param pin port/pin object to tell the switch which hardware pin to use.
\param update_rate Does nothing. Backwards compatibility until next breaking update.
\param t switch type -- Default: TYPE_MOMENTARY
\param pol switch polarity -- Default: POLARITY_INVERTED
\param pu switch pull up/down -- Default: PULL_UP
*/
void Init(int pin,
float update_rate,
Type t,
Polarity pol,
uint8_t mode = INPUT_PULLUP);
/**
Simplified Init.
\param pin port/pin object to tell the switch which hardware pin to use.
\param update_rate Left for backwards compatibility until next breaking change.
*/
void Init(int pin, float update_rate = 0.f);
/**
Called at update_rate to debounce and handle timing for the switch.
In order for events not to be missed, its important that the Edge/Pressed checks
be made at the same rate as the debounce function is being called.
*/
void Debounce();
/** \return true if a button was just pressed. */
inline bool RisingEdge() const { return updated_ ? state_ == 0x7f : false; }
/** \return true if the button was just released */
inline bool FallingEdge() const {
return updated_ ? state_ == 0x80 : false;
}
/** \return true if the button is held down (or if the toggle is on) */
inline bool Pressed() const { return state_ == 0xff; }
/** \return true if the button is held down, without debouncing */
inline bool RawState() {
const bool raw = digitalRead(pin_);
return flip_ ? !raw : raw;
}
/** \return the time in milliseconds that the button has been held (or toggle has been on) */
inline float TimeHeldMs() const {
return Pressed() ? millis() - rising_edge_time_ : 0;
}
/** Left for backwards compatability until next breaking change
* \param update_rate Doesn't do anything
*/
inline void SetUpdateRate(float update_rate) {}
private:
uint32_t last_update_;
bool updated_;
Type t_;
uint8_t state_;
bool flip_;
float rising_edge_time_;
int pin_;
};
#endif