#define BUTTON_PIN A0 // Define the Button readState pin.
#define LED_PIN 7 // Define the LED output pin.
#define DEFAULT_DEBOUNCE_PERIOD 10UL // // Debounce Delay 10 milliseconds
enum state_t : bool {
PRESSED = true,
RELEASED = false
};
typedef struct {
// TODO: DEFINE THE OBJECT MEMBERS
bool toggle;
} Object;
typedef struct {
private:
bool state; //
bool input; // Enable Timer On Variable
unsigned long startTime; // Retrigable start time
typedef void (*CallbackFunction)(Object *obj, bool state); // Callback Function Pointer
CallbackFunction callbackFunction;
Object *object;
public:
// Timer On Function
void onPressed(CallbackFunction function, Object *obj) {
callbackFunction = function;
object = obj;
}
void pressed(bool bounce, const unsigned long timeDelay = DEFAULT_DEBOUNCE_PERIOD) {
//If a time on the done is "false"
bool prevState = state;
if (bounce) {
state = true;
} else {
if (state) {
unsigned long currTime = millis();
// Reload start time by retrigable
if (input) {
startTime = currTime; // Set start time with current time in milliseconds
}
unsigned long elapsedTime = currTime - startTime;
// If elapsed time greater than or equal to the time delay
if (elapsedTime >= timeDelay) {
state = false;
}
}
}
if (prevState != state) {
if (callbackFunction) {
callbackFunction(object, state);
}
}
input = bounce;
}
} pressed_t;
pressed_t button;
Object object;
bool toggle;
void EventOnPressed(Object *obj);
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
button.onPressed(EventOnPressed, &object);
}
void loop() {
button.pressed(!digitalRead(BUTTON_PIN));
digitalWrite(LED_PIN, object.toggle);
}
void EventOnPressed(Object *obj, bool state) {
// TODO: IMPLEMENT EVENT ON PRESSED
if (state == PRESSED)
obj->toggle = !obj->toggle;
}