// https://wokwi.com/projects/404496189354172417
// State Change detection with verbose serial output
/*
State change detection (edge detection)
Often, you don't need to know the state of a digital input all the time, but
you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.
This example shows how to detect when a button or button changes from off to on
and on to off.
The circuit:
- pushbutton attached to pin 2 and Ground
- LED attached from pin 13 to ground through 220 ohm resistor (or use the
built-in LED on most Arduino boards)
created 27 Sep 2005
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
https://docs.arduino.cc/built-in-examples/digital/StateChangeDetection/
*/
// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT_PULLUP);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(115200);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
uint32_t currentMillis = millis();
static uint32_t lastChangeMs = 0;
bool changed = false,rose=false, fell = false;
// compare the buttonState to its previous state
if (buttonState != lastButtonState && currentMillis - lastChangeMs > 5 ) { // changed?
changed = true;
// if the state has changed, increment the counter
if (buttonState == LOW) { // fell?
fell = true;
// if the current state is LOW then the button went from off to on:
buttonPushCounter++;
Serial.print("b#");
Serial.print(buttonPushCounter);
Serial.print(":");
} else { // RISE
rose = true;
// if the current state is HIGH then the button went from on to off:
Serial.print("B");
}
// record last change and time to limit bouncing
lastButtonState = buttonState;
lastChangeMs = currentMillis;
}
// turns on the LED every four button pushes by checking the modulo of the
// button push counter. the modulo function gives you the remainder of the
// division of two numbers:
if (fell) {
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
Serial.print("\nLedOn");
} else {
digitalWrite(ledPin, LOW);
Serial.print("LedOff, ");
}
}
report();
// save the current state as the last state, for next time through the loop
// lastButtonState = buttonState;
}
void report(void) {
const unsigned interval = 500;
static uint32_t lastReport = 0;
static int lastState = -1;
uint32_t now = millis();
if (now - lastReport > interval) {
lastReport = now;
Serial.print("");
}
}