/***********************************************
USE A MOMENTARY PUSHBUTTON AS A TOGGLE SWITCH:
The button is connected from input pin to GND.
INPUT_PULLUP and debouncing are pre-configured.
The built in LED changes state as configured.
**********************************************/
#include <Toggle.h> // does what the name says: include the code that is inside the file Toggle.h AND the file Toggle.cpp
const byte buttonPin = 2;
const byte ledPin = LED_BUILTIN;
byte actualButtonState;
boolean lastButtonState;
Toggle button(buttonPin);
void setup() {
Serial.begin(115200); // 115200 is the modern standard baudrate
Serial.println("Setup-Start");
button.begin(buttonPin); // create the button-"object"
button.setToggleState(0); // set initial state 0 or 1
button.setToggleTrigger(0); // set trigger onPress: 0, or onRelease: 1
pinMode(ledPin, OUTPUT);
}
void loop() {
// this line must be called at high frequency = at least 100 times per second.
// Avoid using delay() whenever you want a QUICK reaction on a button-press
button.poll(); // function-call with the code to read-in the button-state
actualButtonState = button.toggle();
digitalWrite(ledPin, actualButtonState);
printButtonStateOnlyOnce();
}
void printButtonStateOnlyOnce() {
// does what the function name says
if (lastButtonState != actualButtonState) {
if (actualButtonState == HIGH) {
Serial.println("Button is in ON-state now");
}
else {
Serial.println("Button is in OFF-state now");
}
lastButtonState = actualButtonState; // update lastButtonState => print only once per state-change
}
// exits without printing if lastButtonState and actualButtonState have the same value
// the if-condition if (lastButtonState != actualButtonState) checks for UN-equalitiy
// the "!=" is the UN-equal-operator
// in words: if value of variable lastButtonState is unequal to value of variable actualButtonState
}