If Condition problem with pin initialisation

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi, i'm trying to set a single pin high inside a If condition loop, like

 

while(1)
    {
                           
     a[0]=0xff; 
if(PORTD |= (1 << PD1))              
      {   
         PORTC= 0xFF;          //Turns ON All LEDs
         _delay_ms(1000); 

       if(PORTD |= (1 << PD7))                 
           {
               a[2]=1;
               PORTC ^= 0xFF;                      // Turns ON All LEDs
              _delay_ms(1000);                       // long enough for human eye
                        
            }
        
           else
              {
                    a[2]=0;

              }  

    }

 

 

but the problem is that the LED is high even when the condition is not being executed. That is when the "PROGRAMMER" is just connected to ATMEGA32U4, the 5v makes the LED condition execute even without running the actual program. I dont know why the LED starts glowing when Vcc and IF conditions are not even executed.

Please help me.

Last Edited: Wed. Sep 28, 2016 - 09:06 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

To read pins you read PIND not PORTD (the output/pull-up register).

 

Oh and this syntax:

if(PORTD |= (1 << PD1))              

makes no sense anyway - you don't want to base the condition on the assignment of a single bit! I suggest you would want to use:

if(PIND & (1 << PD1))              

 

Last Edited: Wed. Sep 28, 2016 - 09:28 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

1. The conditions in the if-s are always true because you use OR and assignment operator (|=) and I guess AND operator (&) should be used assuming that you want to test the value of one bit.

2. PORTD is the register to set state of the microcontroller pins configured as output. I guess PIND is the register you should use.

 

So I think the condition (PORTD |= (1 << PD1)) should be changed to (PIND & (1 << PD1)) and (PORTD |= (1 << PD7)) should be changed to (PIND & (1 << PD7)).