I have two files, the first file is a library
that I use to handle push buttons
and initialize it and the second is where I handle my code and change LED
state when push button
is pressed, but my code doesn't work, I'm using Atmega32A
micro-controller.
my library code:
#ifndef ButtonLibrary
#define ButtonLibrary
#ifndef numberOfButtons
#define numberOfButtons 2
#endif
#ifndef bit_is_clear
#define bit_is_clear(sfr, bit) (!(_SFR_BYTE(sfr) & _BV(bit)))
#endif
#include <avr/io.h>
char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel);
void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection);
void initialize_led(int pinofled, unsigned char port, unsigned char datadirection);
void change_led_state(int pinofled, unsigned char port);
char pressed[numberOfButtons];
int pressed_confidence_level[numberOfButtons];
int released_confidence_level[numberOfButtons];
void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection)
{
datadirection &= ~(1 << pinofbutton);
port |= 1 << pinofbutton;
}
void initialize_led(int pinofled, unsigned char port, unsigned char datadirection)
{
datadirection |= 1 << pinofled;
port &= ~(1 << pinofled);
}
void change_led_state(int pinofled, unsigned char port)
{
port ^= (1 << pinofled);
}
char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel)
{
if(bit_is_clear(pinofbutton, portbit))
{
pressed_confidence_level[buttonnumber] ++;
released_confidence_level[buttonnumber] = 0;
if(pressed_confidence_level[buttonnumber] > confidencelevel)
{
if(pressed[buttonnumber] ==0)
{
pressed[buttonnumber] = 1;
return 1;
}
pressed_confidence_level[buttonnumber] = 0;
}
}
//button isn't pressed
else
{
released_confidence_level[buttonnumber] ++;
pressed_confidence_level[buttonnumber] = 0;
if(released_confidence_level[buttonnumber] > confidencelevel)
{
pressed[buttonnumber] = 0;
released_confidence_level[buttonnumber] = 0;
}
}
return 0;
}
#endif
my main code:
#define F_CPU 1000000UL
#include <stdio.h>
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>
#include "ButtonLibrary.h"
int main(void)
{
initialize_button(PIND4, PORTD, DDRD);
initialize_button(PIND3, PORTD, DDRD);
initialize_led(PINC7, PORTC, DDRC);
initialize_led(PINC6, PORTC, DDRC);
while(1)
{
if(ButtonPressed(0, PIND, 3, 500) == 1)
{
change_led_state(PINC6, PORTC);
}
if(ButtonPressed(1, PIND, 4, 500) == 1)
{
change_led_state(PINC7, PORTC);
}
}
}
when I press the push button
nothing happens, I think there is something wrong in my initialize
functions or change_led_state
function but I don't know it.