Skip to content

Instantly share code, notes, and snippets.

@fearthecowboy
Last active December 9, 2018 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fearthecowboy/99085a7ccacded8de4d55206fa7007e0 to your computer and use it in GitHub Desktop.
Save fearthecowboy/99085a7ccacded8de4d55206fa7007e0 to your computer and use it in GitHub Desktop.
Switch device
#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