Newer
Older
#include <avr/io.h>
#define led_pin (1 << PB2)
#define button_pin (1 << PA7)
int main(void) {
// Set the clock prescaler to 1.
CLKPR = (1 << CLKPCE);
CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
// Set the 8 bit timer's prescaler to 1/1024.
TCCR0B |= 0b00000101;
// Configure led_pin as an output.
DDRB |= led_pin;
DDRA &= ~button_pin;
// Activate button_pin's pullup resistor.
PORTA |= button_pin;
int bouncy_switch_state = 0;
int debounced_switch_state = 0;
while (1) {
// Use the timer to count how long it's been since button_pin changed state.
if ((PINA & button_pin) != bouncy_switch_state) {
bouncy_switch_state = PINA & button_pin;
TCNT0 = 0;
}
// If it's been 10ms or more since PA7 changed state, it's not bouncing.
if (TCNT0 >= 195) {
// It's been 10ms since the switch changed.
if (bouncy_switch_state != debounced_switch_state) {
debounced_switch_state = bouncy_switch_state;
// If the button is newly pressed, toggle the LED.
if (debounced_switch_state == 0) {
PORTB ^= led_pin;
}
}
}
}
return 0;
}