Possible options is to simplify the while loops
- while ((PIND & B00100000) == 0 && ~PIND & B00000100) -
as PIND is read twice. (once inverted:)
OK lets give it another try
void _isrd2()
{
byte bn = 1;
byte rec = 0;
byte reg = PIND;
while (~reg & B00000100)
{
while ((reg & B00100000) == 0 && ~reg & B00000100) { reg = PIND; };
if (reg & B01000000)
{
rec += bn;
}
bn = bn << 1;
while ((reg & B00100000) == B00100000 && ~reg & B00000100 ) { reg = PIND; };
}
flag = rec;
}