Maybe simple matter, but causes some troubles.
Do you have any effective and simple ways for switch bouncing elliminations? I'm doing an experiment and I've connected micro-switch to a digital I/O in AVR and LED for the testing, and I'm struggling with it. I need method which works in background (not delay()) and not very sophisticated. Just a simple way.
So far I tried those ways:
1.
#include <avr/io.h>
#define LED (1<<PB5)
#define BUTTON (1<<PD0)
uint8_t key_lock = 0;
int main()
{
DDRB |= (1<<LED);
DDRD &= ~(1<<BUTTON);
PORTD |= (1<<BUTTON);
while(1)
{
if (!key_lock && !(PIND & BUTTON))
{
key_lock = 1;
PORTB ^= LED;
}
else if (key_lock && (PIND && BUTTON))
{
key_lock++;
}
}
}
2.
#include <avr/io.h>
#include <avr/interrupt.h>
#define LED (1<<PB5)
#define BUTTON (1<<PD0)
volatile bool state_but = false;
int main()
{
DDRB |= (1<<LED);
DDRD &= ~(1<<BUTTON);
PORTD |= (1<<BUTTON);
// Timera0 overflow
//F_CPU = 16MHz. time interrupt 16 ms
TCCR0B |= (1<<CS02) | (1<<CS00);
TIMSK0 |= (1<<TOIE0);
sei();
while(1)
{
if (state_but == 1)
PORTB ^= LED;
}
}
ISR (TIMER0_OVF_vect)
{
static uint8_t state_last = 0, state_new;
//1- ON, 0 - OFF
state_new = (~PIND & BUTTON);
if (state_last == state_new)
state_but = state_new;
state_last = state_new;
}
3.
#include <avr/io.h>
#include <avr/interrupt.h>
#define LED (1<<PB5)
#define BUTTON (1<<PD0)
volatile uint8_t counter;
int main()
{
DDRB |= (1<<LED);
DDRD &= ~(1<<BUTTON);
PORTD |= (1<<BUTTON);
// Timera0 overflow
//F_CPU = 16MHz. time interrupt 16ms
TCCR0B |= (1<<CS02) | (1<<CS00);
TIMSK0 |= (1<<TOIE0);
sei();
while(1)
{
if (counter == 2)
PORTB ^= LED;
}
}
ISR (TIMER0_OVF_vect)
{
if (!(PIND & BUTTON))
{
counter++;
}
else
{
counter = 0;
}
if (counter > 2) counter = 0;
}
And none of those works so good. Sometimes when I push the button it appears random states and LED blinks without control.
I need to add that I'm using ATmega 2560 (Arduino MEGA) but programing only in C, as you can see.
Any ideas?