Confusion using digitalRead and internal pull up resistors

dhenry:
It is a little bit more complicated than that.

A few things at work:

  1. AVR port behavior. The datasheet says that when a pin is configured as input, writing a '1' to it activates the pull-up. pinMode() follows that to establish pull-up. So writing a '1' to the port after having turned it into input activates the pull-up. That's what your 1st block of code does.
  2. capacitance: In the 2nd block of code, the port is (presumed) high before it was turned into input. When the port was high, it has charged up pin capacitance or any stray capacitance on that pin. Once you have it turned into (high impedance) input, the charges stored on those capacitance start to discharge, in part through your read action. Over time, it reads logic '0'. You can test that for example by putting a larger capacitance on that (the pin capacitance is around 7pf), and you will see that it reads '1' longer.

The 2nd approach actually serves as the basis for some capacitance meter.

I understand how that would happen. I was just thinking back to when I read the data sheet years ago, I seem to recall that setting the port bits to one and then exposing them by setting the data direction register would cause the pins to either come on as a weak pull-up or a strong pull up depending on whether you wrote ones or zeros to the data direction register. I didn't realize that by setting pinMode from OUTPUT to INPUT causes the port bits to be cleared when the DDRx bits are cleared.