is calling PinMode() useful outside Setup()

Hi guys,

I was wondering, is there any good reason to define input/output pin using PinMode() outside of Setup()? Does it make sense on a useful way? I cannot figure a good reason of wanting to change a pin direction or capability for a given hardware configuration except at startup.

Thanks!

Yes, when you want the pin to switch between output and input, vice versa, for external devices.

Example:
https://forum.arduino.cc/index.php?topic=439838.0

See post 334:
https://forum.arduino.cc/index.php?topic=445951.msg3336467#msg3336467

I can't think of any reason to do that but I'm are some valid-logical reasons.

You have to be careful switching between input & output because you can end-up with to outputs connected together "fighting" each other.

Thanks for the examples larryd!
Make sense, I didn't thought about that type of configuration.

pinMode() is used to implement a "virtual open-collector" output mode. Given that the pin is written LOW - and not changed - then setting it as INPUT gives the open-collector logic HIGH where there is a pull-up provided and setting it as OUTPUT pulls it LOW against the pull-up.

Charlieplexing!

PaulRB:
Charlieplexing!

That would be a good example, actually "Tri-State" rather than open collector.

My EC sensor reading depends on switching modes.

Some ultrasound sensors have a single trigger/echo pin which requires dynamic INPUT/OUTPUT switching.

OneWire and similar protocols (like the DHT sensors) will also require switching input/output, as does the SDA line of I2C (that'll be the open collector trick as mentioned in #4).

That gives me a lot to explore, thanks a lot for answering my question guys!

For those interested I asked because I am coding a (very small) x86 flavoured CPU emulator for arduino to be able to execute simple assembly programs uploaded on the fly, and I was wondering if providing an access to PinMode within the assembly language was useful. I guess I have my answer :slight_smile: