MIKR/lectures/Timer/timer-debouncer.c

56 lines
1.0 KiB
C
Raw Normal View History

2024-04-16 20:18:18 +02:00
#include <avr/io.h>
#include <avr/interrupt.h>
volatile uint8_t button_reset_counter;
volatile uint8_t button_press_count;
// decrease reset_counter until 0
ISR(TIMER2_OVF_vect)
{
button_reset_counter -= button_reset_counter == 0 ? 0 : 1;
}
// update press_counter on interrupt if reset == 0
ISR(PCINT2_vect){
if (button_reset_counter == 0){
button_press_count++;
button_reset_counter = 20;
if(button_press_count % 2 == 0){
PORTD &= ~(1<<5);
}else{
PORTD |= (1<<5);
}
}
}
int main(void) {
// C7 as input for external interrupt
DDRC &= ~_BV(DDC7);
PORTC |= _BV(PORTC7);
// D5 as output
DDRD = _BV(PD5);
PORTD = _BV(PD5);
// TIMER 2 setup
TCCR2B |= _BV(CS22) | _BV(CS21) | _BV(CS20);
TIMSK2 |= _BV(TOIE2);
cli();
// rising edge interrupt on INT2
EICRA |= _BV(ISC20);
EIMSK |= _BV(INT2);
// enable external interrupt for pin 23 - PC7
PCMSK2 |= _BV(PCINT23);
PCICR |= _BV(PCIE2);
sei();
for(;;){}
return 0;
}