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.

while(!(UCSRA & (1<<RXC)));


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


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

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


             case 69:{


              case 70:{

              case 71:{
              case 72:{




please anyone help me to solve this problem.


closed as unclear what you're asking by Chris Stratton, RoyC, Dmitry Grigoryev, laptop2d, Bimpelrekkie Nov 5 '18 at 17:36

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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

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);
  • \$\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.