digitalRead question

Good afternoon…
Does digitalRead() work with a pin that is an output??

@ridgerunnersjw, I believe reading a pin set as OUTPUT will return the currently set output state for that pin.

3 Likes

Hey Paul, I read somewhere that this depends on the circuit of the MCU, could it be?
It had something to do with the input circuitry going in high impedance mode and not really connected to the pin when it is configured as OUTPUT. I could not find the resource where I read this.

Have you heard something similar? Maybe this is ancient information, please disregard if so.
Thanks!

Although I don’t know of any, it may well be that some MCUs actually read their own output voltage.
However, the far more common strategy is the one Paul condensed in a single sentence: To read the connected port registers to make an “educated guess” about the “supposed” state of the pin.
I’m pretty sure if you have a pin set to HIGH and then short it to ground externally, in the few moments the GPIO has left to live, a digitalRead() would return HIGH although the actual level would be LOW.

Here are the respective portions of the device OS for Gen2 (calling this) and for Gen3 (calling this).

2 Likes

So when I look at the Particle documentation what command would I use to read the pin?

Very common scenario: You have two blocks of code that could drive Pin A. These two blocks of code are controlled by asynchronous events (say two different buttons). If one button is pushed you want to operate one section of code…If the second button is pushed you want to operate another. But both routines want to drive pin A. They may however want to test Pin A for it’s state to decide whether to leave it alone or flip it…

How would you do that in the command list that Particle has exposed to the user??

As your initial question suggests and answers by @peekay123 and myself confirm: digitalRead().

Alternatively you could use a variable to hold the current (aka last set) state and use that instead. This may improve readability of your code.
This also opens the possibility to hand off the actual calling of digitalWrite() to one central “server function” to increase stability by avoiding concurrency and possible race conditions (particularly when employing async prorgramming).

1 Like