0
\$\begingroup\$

I have written code to switch ON/OFF some LED light connected different I/O pins of same PORT (i.e PORTD) of atmega8 microcontroller. This process is performed using android app by sending different byte through USART. When a data byte is sent then the corresponding LED is ON. When two or more LED is ON by sending their corresponsing data bye then if to switch OFF a specified LED, a specified byte is sent ,the whole LED is OFF. if i use two separate PORT (i.e PORTC and PORTD) then i get exact output but in this case i can use only one pin of PORTD and one pin of PORTC for two LED ON/OFF. if i use more than two pin, the above fault occur. My code is below.

ISR(USART_RXC_vect)
{
while(!(UCSRA & (1<<RXC)));
rec=UDR;

        switch(rec)           
{

              case 65:{
              PORTD |=1<<4;

             }break;



              case 66:{
               PORTD |=1<<5;       
             }break;

              case 67:{
                PORTD |=1<<6;       
             }break;
              case 68:{
              PORTD |=1<<7;

             }break;


             case 69:{
               PORTD&=~1<<4;

             }break;



              case 70:{
               PORTD&=~1<<5;       
             }break;

              case 71:{
                PORTC&=~1<<6;      
             }break;
              case 72:{
              PORTB&=~1<<7;

             }break;


             }

}

please anyone help me to solve this problem.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ The problem is you have PORTD &= ~ 1 < 4 where it should be << instead of <. \$\endgroup\$ – MarkU Oct 29 '18 at 2:42
  • \$\begingroup\$ I wretten PORTD &= ~1<<4; But same problem occur. \$\endgroup\$ – Muzahid Karim Oct 29 '18 at 2:56
  • \$\begingroup\$ You need a bracket around the shift, so ~(1<<4). The ~ operator is higher precedence, so what you're writing is equivalent to 0<<4. Have a look here: en.cppreference.com/w/c/language/operator_precedence \$\endgroup\$ – awjlogan Oct 30 '18 at 12:30
1
\$\begingroup\$

The expression

PORTD &= ~ 1 << 4;

is actually interpreted as

PORTD &= ((~1) << 4);

due to operator precedence. In C++, the unary ~ operator is higher priority than binary << operator. See https://en.cppreference.com/w/cpp/language/operator_precedence

Fix this by using parenthesis to enclose the 1 << 4 expression:

PORTD &= ~(1 << 4);
\$\endgroup\$
1
  • \$\begingroup\$ thanks a lot brother. I'm facing this problem for one month. At last you helped me solve it. \$\endgroup\$ – Muzahid Karim Oct 29 '18 at 4:21

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