I have written a code that detects a button press, first time the button is pressed a LED glows and when next time it is pressed , the LED should switch off, in the same way if third time it is pressed the LED should again glow.
The problem is , the controller is able to detect the button press but instead of switching on the LED for long time, it just momentarily switches it ON then it again switches OFF. And further button presses are not detected.
Below is the code:
#include <avr/io.h>
#include <avr/delay.h>
void glow();
void off();
void switchScan();
int main()
{
DDRA=0x02; // 0000 0010 --> BIT 0=connected to switch whose other pin is connected to ground,, and BIT 1 is connected to LED with other pin of led connected to ground
PORTA=0x01; // 0000 0001---> Switch Input pulled up and LED output pulled down
while(1)
{
switchScan();
}
return 0;
}
void glow()
{
PORTA=PORTA|(1<<1);
}
void off()
{
PORTA=PORTA&(~(1<<1));
}
void switchScan()
{
static int counter=0;
if(~(PINA & 0x01))
{
counter++;
if(counter < 2)
glow();
else
{
counter--;
off();
}
}
}