0

I am trying to make a button debounce software by the help of an led toggle function that returns a different boolean each time which i got by asking the question before but that never worked :

#include <avr/io.h>

bool ledToggle();

int main(void)
{   
    DDRB |= (1 << 0); 
    DDRB &= ~(1 << 0); 

    while(1)
    {   
        //TODO:: Please write your application code                 

        if (ledToggle() == true)
        {       
            //led on
            PORTB |= (1 << 0);          
        }else{          
            //led off
            PORTB &= ~(1 << 0);         
        }       
    }
}

bool ledToggle()
{
    static bool state = false;  
    if(bit_is_clear(PINB, 1)){
        state = !state;
    }

    return state;   
}

EDIT

I get no errors or anything when I try to compile it just doesn't work...

user3407319
  • 227
  • 2
  • 10

2 Answers2

0

In the second line of main () you are mistakenly setting the LED port instead of the BUTTON port as an input.

I suggest using defines as a way of making this kind of mistakes less likely:

#define LED    0
#define BUTTON 1

DDRB |= (1 << LED);
DDRB &= ~(1 << BUTTON);
0

I don't recognize in which way this code would debounce a switch connected to Port B / 1. Debouncing means to

  • check and store the key logic state
  • wait a certain amount of time (depending on hardware, 5 - 50 ms)
  • compare the (now) logic state with what was read before
  • if equal the (now) logic state is the debounced key state

Provided the program is functioning well, the LED would bounce at the same pace as the switch.

In your bool ledToggle() I suggest you declare static volatile bool state; to ensure the variable is created in RAM (rather than a CPU register)

MikeD
  • 8,861
  • 2
  • 28
  • 50