Can you change the pinMode of a variable twice?

Lets say a variable was declared in the stetup function as OUTPUT, like:

pinMode(x, OUTPUT);

later in the loop function, can I change the pinMode of that same variable to INPUT, like:

pinMode(x, INPUT);

and maybe back to 'OUTPUT'? Will there be any problems, or am I good to go?

you can do that as often as you wish, provided you can keep it straight in your mind.

Also, think about what's going on on the hardware side, though. An input has no well defined level, so what are the other elements of the circuit going to do? Conversely, when it's an output, it's driving whatever load is out there - if it's driving another output, from the Arduino or from a sensor, you could be looking at a scenario that could damage your Arduino.

1 Like

I hope you have a very good reason for doing this...

Of course, an input is normally connected to an output and vice-versa so it usually doesn't make sense to witch the pin's function.

It can be "dangerous" if you connect an output to an output. If one output writes high and one writes low at the same time you can burn-up stuff. (You can do it safely with open-collector or open-drain connections but that's not built-into the Arduino.)

Connecting two inputs together doesn't hurt anything. But It's not that useful unless something else is connected to control the state of the input.

1 Like

There are use cases for doing this, but they're few and far between. One is to use a single output to achieve 4 states with a two-pin red-green bipolar LED, as was hashed over in this topic:

The states are Red, Green, Yellow (by alternating at a high rate), and Off. Off is achieved by simply making the pin an input (with pullup, as noted towards the end of that topic).

https://docs.arduino.cc/retired/hacking/software/PortManipulation/

1 Like

Another is a tri-stating a pin for a capacitance meter:

https://docs.arduino.cc/tutorials/generic/capacitance-meter/

2 Likes

You seem quite confused, and so far no-one has realised this.

With that line of code, you are not declaring a variable. Declaring a variable is done with a line like this:

int x = 5;

What your line of code does is set the mode of an Arduino pin. You can do this as many times as you like in setup() or loop(). But as already pointed out, there are only a very small number of good reasons to do it more than once, so if you think you need to do it more than once, please explain why because you may be confused about that also.

3 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.