# Different I/O pins of same PORT of ATMEGA8 not providing exact output [closed]

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.

• The problem is you have PORTD &= ~ 1 < 4 where it should be << instead of <. – MarkU Oct 29 '18 at 2:42
• I wretten PORTD &= ~1<<4; But same problem occur. – Muzahid Karim Oct 29 '18 at 2:56
• 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 – 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);

• thanks a lot brother. I'm facing this problem for one month. At last you helped me solve it. – Muzahid Karim Oct 29 '18 at 4:21