Electronic – LED on button push ATMEGA328p

atmega328pbuttonled

I am using a Tinkerkit button as input to Arduino PORTD pin0 and expect an output on PORTC, pin0 as output.

Code:

void wait_for_button()
{

  if( (PORTD & (1<<PD0)) )
      PORTC|=(1<<PC0);
  else
      PORTC|=~(1<<PC0);

}
int main (void)
{

  DDRD=0x00;   //PORTD pin 0 as input
  PORTD=0x00;
  DDRC=0xFF;   //PORTC as output
  PORTC=0x00;

   while(1)
   {
     _delay_ms(200);
     wait_for_button();
   }

}

HW Setup:
http://ibb.co/ek6R7a

TinkerKit:
http://www.mouser.com/catalog/specsheets/TinkerKitPushButton.pdf

LED does not lightup on button push. what am i doing wrong?

Best Answer

The problem is in the code that detects a button press. You wrote:

if( (PORTD & (1<<PD0)) )

However, you should write this instead:

if(PIND & (1 << PD0))

This is because PORTD is the output register. It will only reflect values that you write to the pin, not an external voltage. PIND is the input register, which reflects the voltage read at the pin.

And as brhans pointed out, PORTC |= ~(1 << PC0); should be PORTC &= ~(1 << PC0); instead.

Related Topic