|
1 |
| -// Code to Debounce signal and avoid automatic bouncing |
2 |
| -// link to simulator |
3 |
| -// |
4 |
| - |
5 |
| -const int btn_pin = 2; |
6 |
| -const int debounce_delay =50; // ms |
7 |
| -// we require debounce to make sure that microcontroller does not |
8 |
| -// consider state change automatically |
9 |
| - |
10 |
| -// Globals |
11 |
| - int counter =0; |
12 |
| - int btn_state = HIGH; |
13 |
| - int btn_prev = HIGH; |
14 |
| - unsigned long last_debounce_time = 0; |
15 |
| - |
16 |
| -void setup() { |
17 |
| - pinMode(btn_pin, INPUT_PULLUP); |
18 |
| - Serial.begin(9600); |
19 |
| - |
20 |
| -} |
21 |
| - |
22 |
| -void loop() { |
23 |
| - int btn_read = digitalRead(btn_pin); |
24 |
| - |
25 |
| - // when button chages state |
26 |
| - if( btn_read != btn_prev ){ |
27 |
| - last_debounce_time = millis(); |
28 |
| - } |
29 |
| - // wait before checking the state of button again |
30 |
| - if(millis() > (last_debounce_time + debounce_delay)){ |
31 |
| - if( btn_read != btn_state){ |
32 |
| - btn_state = btn_read; |
33 |
| - if(btn_state == LOW){ |
34 |
| - counter++; |
35 |
| - Serial.println(counter); |
36 |
| - |
37 |
| - } |
38 |
| - } |
39 |
| - } |
40 |
| -// remeber the previous state for next loop() |
41 |
| - btn_prev = btn_read; |
| 1 | +// Code to Debounce signal and avoid automatic bouncing |
| 2 | +// link to simulator |
| 3 | +// https://www.tinkercad.com/things/d7pgjOaPr6u-debouncingcounter/editel |
| 4 | + |
| 5 | +const int btn_pin = 2; |
| 6 | +const int debounce_delay =50; // ms |
| 7 | +// we require debounce to make sure that microcontroller does not |
| 8 | +// consider state change automatically |
| 9 | + |
| 10 | +// Globals |
| 11 | + int counter =0; |
| 12 | + int btn_state = HIGH; |
| 13 | + int btn_prev = HIGH; |
| 14 | + unsigned long last_debounce_time = 0; |
| 15 | + |
| 16 | +void setup() { |
| 17 | + pinMode(btn_pin, INPUT_PULLUP); |
| 18 | + Serial.begin(9600); |
| 19 | + |
| 20 | +} |
| 21 | + |
| 22 | +void loop() { |
| 23 | + int btn_read = digitalRead(btn_pin); |
| 24 | + |
| 25 | + // when button chages state |
| 26 | + if( btn_read != btn_prev ){ |
| 27 | + last_debounce_time = millis(); |
| 28 | + } |
| 29 | + // wait before checking the state of button again |
| 30 | + if(millis() > (last_debounce_time + debounce_delay)){ |
| 31 | + if( btn_read != btn_state){ |
| 32 | + btn_state = btn_read; |
| 33 | + if(btn_state == LOW){ |
| 34 | + counter++; |
| 35 | + Serial.println(counter); |
| 36 | + |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | +// remeber the previous state for next loop() |
| 41 | + btn_prev = btn_read; |
42 | 42 | }
|
0 commit comments