Need help with pushbutton on atmega8

atmegaavrc

This is what I have:

Atmega 8 wired for programming, confirmed working, programmer is my power supply.
2 leds connected via 470Ohm pull up reisistors to ports PORTB0, PORTB1 and to GROUND, working.
Pushbutton wired directly from VCC to PORT7D. My problem is that pressing button doesn't do anything. I have measured voltage levels at PORT7D and it is 4.96V when I press the button, otherwise it is zero.
Please find the program below and help me:

#define F_CPU 1000000UL

#include <avr/io.h>
#include <util/delay.h>

int
main (void)
{
    DDRB = 0xFF;
    DDRD = 0x00;


    while(1) 
    {

        if( (PORTD & (1<<PORTD7)) == 1){  
        PORTB =   (1 <<PORTB1);
        _delay_ms(200);
        PORTB = (1 << PORTB0) ;
        _delay_ms(200);
        }else{ PORTB=0xff;}
    }
} 

Best Answer

Pushbutton wired directly from VCC to PORT7D.

There's one problem. When the button is pushed, the input is high. When the button is released, the input is floating. This is bad.

Configure the internal pullup on the pin, and then tie the button to ground. The input will be low when the button is pushed, and high when released.

if( (PORTD & (1<<PORTD7)) == 1)

And there's two more. The input value is on PINx, not PORTx. And that equality check is erroneous.

if (PIND & _BV(PD7))
Related Topic