Pin read problem

When I leave PD2 unconnected, I get a stream of ones, as expected. When I connect PD2 to ground, I get a stream of alternating ones and zeros, instead of the stream of zeros I expected.

What have I done wrong?

#include <avr/io.h>


int main (void) {

  Serial.begin(9600);

  DDRD |= (0 << PD2);
  PORTD |= (1 << PD2);


  for (;;) {
    if (PIND & (1 << PD2)); {
      Serial.println("1");
    }
    if (!(PIND & (1 << PD2))) {
      Serial.println("0");
    }
  }
}

Thanks for any help.

No idea as direct port manipulation is not something I regularly use.

But OR'ing DDRD with 0 does not make sense.

DDRD |= (0 << PD2);

Yeah, I’m thinking that doesn’t do what you think it does. Maybe you need to go back and study up on the bitmath. Write that one out and see…

x = 0b11111111

y = x | (0 << 3) == 0b11111111

You can see that or’ing a 0 in doesn’t change anything.

I think you want

DDRD &= ~(1 << PD2);

You’re right, that line does nothing (I included it as a reminder to myself as to what I want that pin to do.

However, commenting out that line makes no difference, because the initial value of all DDRD bits is 0. I still get an alternating stream of ones and zeros.

DDRD |= (0 << PD2);
if (PIND & (1 << PD2)); {

Notice something extra in that line?

I would expect the “1” to print no matter what the value of PIND

Thanks. I suspected it would be some stupid mistake or typo, but I just couldn't see it, even when it was right there in front of me!