I want to connect a normal toggle switch with one of the gpios pins of a tasmotized esp01 with a wire about 20 feet in length. When I tried this before, I lost the GPIO pin mostly due to the high current drawn from GPIO because of the long wire. How can I limit current and protect the gpio and esp completely?
Thanks for the tips. I have seen one more solution to protect GPIO pins which was never mentioned here. This uses optocouplers. The anode or the cathode of the optocoupler can be connected through a switch to vcc or ground respectively. With respect to the optocoupler a series resistance will also needed to be used. The GPio and ground are connected to the 3 and 4 pins. when the switch is engaged, the 3 and 4 pins are connected.
You don't say how your switch is connected.
The standard way to protect a GPIO pin is with a series resistor and ideally a couple of Schottky diodes to clamp it to the supply rails.
Unless you're expecting particularly high voltages or require high speed data then around 100 ohms in series is reasonable.
The diodes go from the input pin to the processors power and ground pins. They are connected so that if the input is between 0 and 3.3 V they are reverse biased and have no effect. But if the input goes above VCC or below GND then the appropriate diode turns on and clamps the voltage. The series resistor limits the current that can flow in this situation and so prevents the diode from getting overloaded. In the image below this means pin 1 of the BAT54-S (the lower right one) goes to GND, pin 2 to 3V3 and pin 3 to your signal. Watch out, different manufacturers sometimes number the pins in different orders.
In theory the diode isn't needed. The chip will include the equivalent diodes internally. However they aren't particularly good ones and will be more susceptible to failure, counting on them is never a good plan. The external ones will clamp sooner and harder and are easier to replace if something does fry.
Just for clarity the resistor is on the outside of the diode. The signal path is: Outside world - resistor - clamping diode - ESP32 pin.