0
\$\begingroup\$

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;}
    }
} 
\$\endgroup\$
2
  • \$\begingroup\$ And how did you configure PORTD? \$\endgroup\$ Oct 30 '14 at 19:30
  • \$\begingroup\$ Dear Ignacio, I suppose it is configured as Input as my code says. \$\endgroup\$
    – zarcel
    Oct 30 '14 at 19:30
1
\$\begingroup\$

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))
\$\endgroup\$
3
  • \$\begingroup\$ Please help me with configuring internal pull up resistor because i can't find anything on the internet, only arduino stuff. Btw, It's constantly 0 when i measure it. Thanks! \$\endgroup\$
    – zarcel
    Oct 30 '14 at 19:42
  • \$\begingroup\$ DDRx&=~(1<<PDy); PORTx|=(1<<PDy); x is your port, y is the pin #. Sets pin to input and pullup high. \$\endgroup\$
    – user34920
    Oct 30 '14 at 19:45
  • \$\begingroup\$ @zarcel: It's in the datasheet, right on the third page of the "I/O Ports" section, in a table conveniently captioned "Port Pin Configurations". \$\endgroup\$ Oct 30 '14 at 19:46
0
\$\begingroup\$

The way you want to hook up a switch to the AVR is like so:

schematic

simulate this circuit – Schematic created using CircuitLab

Lets say this is pin 3 on port B, so the code would look like this:

DDRB&=~(1<<PB3); // Set pin to input
PORTB|=(1<<PB3); // Pullup resistor high
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.