/*
State change detection (edge detection)
https://wokwi.com/projects/391475222059330561
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 from +5V
- 10 kilohm resistor attached to pin 2 from 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/
*/
// Includes
#include "proto_activities.h"
// Constants
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
// Activities
// Recognizes the push of the button and reports it in the output parameter
pa_activity (ButtonPushRecognizer, pa_ctx_tm(), bool& pushed) {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
pa_every ((digitalRead(buttonPin) == HIGH)) {
pushed = true;
pa_pause;
pushed = false;
pa_delay_ms (50);
pa_await (digitalRead(buttonPin) == LOW);
pa_delay_ms (50);
} pa_every_end
} pa_end
// Increments a counter everytime trigger is true
pa_activity (Counter, pa_ctx(), bool trigger, int& counter) {
pa_every (trigger) {
++counter;
} pa_every_end
} pa_end
// Prints the number of button pushes everytime it changes
pa_activity (ButtonPushLogger, pa_ctx(), int trigger, int counter) {
pa_every (trigger) {
Serial.print("number of button pushes: ");
Serial.println(counter);
} pa_every_end
} pa_end
// Drives the led according to the parameter
pa_activity (LedDriver, pa_ctx(), bool on) {
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
pa_repeat {
if (on) {
digitalWrite(ledPin, HIGH);
pa_await (!on);
}
digitalWrite(ledPin, LOW);
pa_await (on);
}
} pa_end
// Sets up and connects the components
pa_activity (Main, pa_ctx(pa_co_res(4); pa_use(ButtonPushRecognizer); pa_use(Counter); pa_use(ButtonPushLogger); pa_use(LedDriver); bool pushed; int counter)) {
pa_co(4) {
pa_with (ButtonPushRecognizer, pa_self.pushed);
pa_with (Counter, pa_self.pushed, pa_self.counter);
pa_with (ButtonPushLogger, pa_self.pushed, pa_self.counter);
pa_with (LedDriver, pa_self.counter % 4 == 0);
} pa_co_end
} pa_end
pa_use(Main);
// Setup and Loop
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
pa_tick(Main);
}