The EventSwitch
class is for standard on/off inputs. Like the EventButton
the switch must be wired between the pin and GND. When the switch is closed (LOW) its state will be 'ON' and when open (HIGH) it will be 'OFF'.
A quick explainer: The switch pin is configured with the microcontroller's internal INPUT_PULLUP
resistor. In this configuration, without anything attached, the pin will read as HIGH because it has been 'pulled up' to the voltage of the board (either 3.3V or 5V). When you attach a switch (or button) that is wired from the pin to GND, if the switch is closed (or the button pressed), the weak pullup resistor is overcome by the closed switch 'pulling' the pin to GND (0V) or LOW.
#include <EventSwitch.h>
// Create an EventSwitch input
EventSwitch mySwitch(18);
// Create a callback handler function
void onSwitchEvent(InputEventType et, EventSwitch& es) {
Serial.print("Switch event fired: ");
Serial.println(es.isOn() ? "ON" : "OFF");
}
void setup() {
Serial.begin(9600);
// Link the switch's callback to function defined above
mySwitch.setCallback(onSwitchEvent);
}
void loop() {
// Call 'update' for every EventSwitch
mySwitch.update();
}
See example Switch.ino for a slightly more detailed sketch.
In addition to the common events (Enabled, Disabled and Idle) the following event types are fired by EventSwitch:
Will be fired after switch is turned on.
Will be fired after switch is turned off.
Construct an EventSwitch
EventSwitch(byte switchPin);
In addition to the common methods the following are available for EventAnalog:
Must be called within loop()
. See common methods for details.
Setup methods are typically called from within setup()
but can be updated at runtime.
See common methods for details.
If your wiring is reversed, you can switch it with this method. The ON
event is fired in place of the OFF
event and vice versa. Default is true
so pass false
to return to 'normal' behaviour.
Returns true if on and off are reversed.
Default is set in the Bounce2 library (currently 10ms)
Returns true if the switch is on.
Returns true if the switch is off.
Directly get the duration of the switch current state from Bounce2
Directly get the previous duration of the switch previous state from Bounce2