Home Code AVR software debounce example

AVR software debounce example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <avr/io.h>
#include <util/delay.h>  
 
/*
    Button click with software debounce
*/
 
int main(void)
{
    DDRB |=  1 << PINB0;      // set PINB0 as output
    PORTB ^= 1 << PINB0;      // xor toggling only PORTB0
    DDRB |=  1 << PINB2;      // set PINB2 as output
     
    DDRB &=  ~(1 << PINB1);   // set PINB1 as input
    PORTB |= 1 << PINB1;      // pull PINB1 high
     
    int press = 0;
    int pressed_cf=0;
    int released_cf=0;
    while(1) // infinite loop
    {
        if(bit_is_clear(PINB,1))
        {
             
            if (pressed_cf++ > 500)
            {
                if (press == 0 )
                {
                    PORTB ^= 1 << PINB0;
                    PORTB ^= 1 << PINB2;
                    press = 1;
                }
                pressed_cf = 0;
            }
        }
        else
        {
            if(released_cf++ > 500)
            {
                press=0;
                released_cf=0;
            }
        }
    }
 
 
 
}

You may also like