I'm creating an electronic "connect the wires" puzzle - similar to that shown:
The idea of the game is that there are a number of sockets and players must insert leads to connect the correct pairs.
My approach at the moment is as follows:
All the sockets are wired to individual pins which are initialised as OUTPUT, and have a digitalWrite(HIGH) signal sent to them in setup().
I have an array that defines the correct pairs of pins that should be connected. So, say {{13, 11}, {12, 8}, {10, 9}}
In each call to loop(), I iterate over the array or pairs and redefine the second pin (the "receiving" pin) as INPUT_PULLUP. Then, I send a digitalWrite(LOW) to the first pin, and test digitalRead() on the receiving pin. If it reads low, I conclude that the pair of pins have been correctly connected. It not, they are not. I then set the signal on the sending pin back to digitalWrite(HIGH) and move on to test the next pin.
Now, this is actually working really well - the logic and performance seem great. My only question/concern is whether there are any issues I should be aware of from reassigning GPIO pins as input/output at runtime (potentially, on every iteration of loop()) like this?
I can't seem to find any examples that do this - people tend to assign a pin's function once in setup() after which it remains for the duration of the project.
There is nothing wrong with reassigning pinModes in loop() as long as you are careful not to connect 2 outputs together, especially one that is HIGH and one that is LOW (short). In fact the Ping (ultrasonic rangefinder) library does this to read a 3 pin sensor (trigger as output and then change pin to input for reading the echo).
Thanks for the reply. Players may attempt to connect any pair of pins so, to prevent the risk you describe, perhaps I should have the default state of all pins to be initialised as INPUT_PULLUP instead of OUTPUT?
Apart from that, it sounds like I can leave the code as-is, changing a single pin to OUTPUT with a LOW signal and checking if that is felt on the correct input pin, then setting back to INPUT_PULLUP before checking the next etc.
So, if players connect the wrong pins, it will only ever be an INPUT_PULLUP to another INPUT_PULLUP and that's safe, right?
For this application you should maybe consider some ESD protection? Maybe only some resistor for each pin? It will also protect from damage if two pins were connected and configured OUTPUT one LOW and the other HIGH by mistake.