Last active
December 9, 2018 06:04
-
-
Save fearthecowboy/99085a7ccacded8de4d55206fa7007e0 to your computer and use it in GitHub Desktop.
Switch device
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include "device.h" | |
// this device represents a switch that can be open or closed. | |
class Switch : public Device { | |
protected: | |
// the pin the switch is connected to. | |
const uint8_t pin; | |
public: | |
// scalar events support ->is(value) | |
ScalarEvent<bool> state; | |
// constructor -- sets up the pin and how often to check | |
Switch(const uint8_t pin, const unsigned long interval = 50) | |
: pin(pin) { | |
pinMode(pin, INPUT); | |
repeat(interval); | |
} | |
// good devices will reset their event listeners when reset | |
// (this happens during state changes) | |
void reset() { | |
state.reset(); | |
} | |
void loop() { | |
// in our loop, all we have to do is check the state of | |
// the pin and let the event manage triggering the handler | |
state.invoke((digitalRead(pin) != HIGH)); | |
} | |
// this lets us have the event on the device directly | |
// so instead of saying: | |
// when( switch->state.is(closed) , { ... } ); | |
// we can just say: | |
// when( switch->is(closed), { ... } ); | |
inline Event& is(bool value) { | |
return state.is(value); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment