2
State change detection (edge detection)
4
Often, you don't need to know the state of a digital input all the time,
5
but you just need to know when the input changes from one state to another.
6
For example, you want to know when a button goes from OFF to ON. This is called
7
state change detection, or edge detection.
9
This example shows how to detect when a button or button changes from off to on
13
* pushbutton attached to pin 2 from +5V
14
* 10K resistor attached to pin 2 from ground
15
* LED attached from pin 13 to ground (or use the built-in LED on
22
http://arduino.cc/en/Tutorial/ButtonStateChange
26
// this constant won't change:
27
const int buttonPin = 2; // the pin that the pushbutton is attached to
28
const int ledPin = 13; // the pin that the LED is attached to
30
// Variables will change:
31
int buttonPushCounter = 0; // counter for the number of button presses
32
int buttonState = 0; // current state of the button
33
int lastButtonState = 0; // previous state of the button
36
// initialize the button pin as a input:
37
pinMode(buttonPin, INPUT);
38
// initialize the LED as an output:
39
pinMode(ledPin, OUTPUT);
40
// initialize serial communication:
46
// read the pushbutton input pin:
47
buttonState = digitalRead(buttonPin);
49
// compare the buttonState to its previous state
50
if (buttonState != lastButtonState) {
51
// if the state has changed, increment the counter
52
if (buttonState == HIGH) {
53
// if the current state is HIGH then the button
54
// wend from off to on:
57
Serial.print("number of button pushes: ");
58
Serial.println(buttonPushCounter, DEC);
61
// if the current state is LOW then the button
62
// wend from on to off:
63
Serial.println("off");
66
// save the current state as the last state,
67
//for next time through the loop
68
lastButtonState = buttonState;
71
// turns on the LED every four button pushes by
72
// checking the modulo of the button push counter.
73
// the modulo function gives you the remainder of
74
// the division of two numbers:
75
if (buttonPushCounter % 4 == 0) {
76
digitalWrite(ledPin, HIGH);
78
digitalWrite(ledPin, LOW);