How do I read the current state of a pin

If Pin 12 is set to OUTPUT and currently the pin output is LOW, how can I read that pins current state?

What have you tried?

You can't. You have to remember what you set it to.

I have a nice little class that abstracts the pin output and provides some helper functions for simple pin manipulation. It also remembers the state you set the pin to for you, and allows you to query it.

https://github.com/majenkotech/Output

AWOL: What have you tried?

No, mainly because I have no idea what you would use to read it.

Well, let's think - you use digitalWrite to write to a pin, so what do you imagine you might use to read one? Hmmm. Conundrum.

if ((PINB & 0b00010000) == 0b00010000){
bit12 = 1;
}
else {bit12 = 0;}

For '328P boards anyway.

AWOL: Well, let's think - you use digitalWrite to write to a pin, so what do you imagine you might use to read one? Hmmm. Conundrum.

IDK, a Kindle or a KOBO?

I just looked at http://arduino.cc/en/Reference/DigitalRead but that doesn't appear to answer the question.

Can an output pin also be an input?

digitalRead() Description Reads the value from a specified digital pin, either HIGH or LOW.

This quote is from the Reference page. It seems unambiguous to me.

The concepts of setting the condition of a pin (OUTPUT or INPUT) and reading (or writing) the value of the pin are not connected to each other. All the details are in the Atmega328 datasheet, but I must say it is not as clearly explained as it could be.

...R

The best reference is to look at the schematic of an IO pin in the data sheet. There you can clearly see that reading a pin and writing a pin are pretty much unconnected.

You write to an output pin and it sets the output value flip-flop PORTxn. You are unable to read that flip-flop.

You read from an input pin and it reads the PINxn buffer.

The PINxn is always available, but the PORTxn is isolated from the pin when DDxn is set to INPUT.

So, digitalRead() doesn't return what you set the pin to, but what the electrical value of the pin is. If you set the pin high, but have a short pulling it low, digitalRead() will return LOW, not HIGH. Also you would probably burn out your IO pin shorting it like that ;)

But that illustrates that what you read from an OUTPUT pin is NOT the same as what you write to it (but it usually is).