]> git.piffa.net Git - arduino/blob - var_sketches/get_started_2/example_03c_button_debouncing/example_03c_button_debouncing.ino
corsi
[arduino] / var_sketches / get_started_2 / example_03c_button_debouncing / example_03c_button_debouncing.ino
1 // Example 03C: Turn on LED when the button is pressed
2 // and keep it on after it is released
3 // including simple de-bouncing
4 // Now with another new and improved formula!!
5  
6
7 const int LED = 13;
8 // the pin for the LED
9 const int BUTTON = 7;
10 // the input pin where the
11 // pushbutton is connected
12 int val = 0;
13 // val will be used to store the state
14 // of the input pin
15 int old_val = 0; // this variable stores the previous
16 // value of "val"
17 int state = 0;
18 // 0 = LED off and 1 = LED on
19 void setup() {
20   pinMode(LED, OUTPUT);
21   // tell Arduino LED is an output
22   pinMode(BUTTON, INPUT); // and BUTTON is an input
23 }
24 void loop(){
25   val = digitalRead(BUTTON); // read input value and store it
26   // yum, fresh
27   // check if there was a transition
28   if ((val == HIGH) && (old_val == LOW)){
29     state = 1 - state;
30     delay(10);
31   }
32   old_val = val; // val is now old, let's store it
33   if (state == 1) {
34     digitalWrite(LED, HIGH); // turn LED ON
35   } 
36   else {
37     digitalWrite(LED, LOW);
38   }
39 }
40
41