When using NodeMCU, I want to toggle the state of GPIO pin, using a physical switch. When the switch is pressed, the switch state should toggle from low to high, or high to low.

I know I need to use interrupts here, however I am unable to find relevant information online. I need help with circuit to implement a switch for GPIO interrupt. What would be ideal resistor value etc.

I forgot to mention, i am using Tasmota firmware on NodeMCU.


  • \$\begingroup\$ Are you really using the NodeMCU in Lua? Or are you using it with the Arduino IDE? \$\endgroup\$ – jDAQ Sep 9 '19 at 4:34
  • 1
    \$\begingroup\$ "I know I need to use interrupts here" no, you almost certainly do not. A switch moved by a human, or even many mechanisms is quite slow in computer terms, polling is typically fine. And where debouncing is needed, polling is often best. You do, however, need a pulling resistor. Perhaps you are confusing the two very distinct concepts? \$\endgroup\$ – Chris Stratton Sep 9 '19 at 5:20
  • \$\begingroup\$ @ChrisStratton Thanks for the update, i missed to mention that i am using Tasmota as the firmware. I need a way for the user to manually override the automated switch. \$\endgroup\$ – Suresh Kumar Sep 9 '19 at 5:58
  • 2
    \$\begingroup\$ You still don't need an interrupt \$\endgroup\$ – Chris Stratton Sep 9 '19 at 6:00

Look at https://nodemcu.readthedocs.io/en/master/modules/gpio/#gpiotrig the usage of the function must be:

   gpio.trig(pin, [type [, callback_function]])

pin is the pin that should trigger the interrupt, using the NodeMCU convention the "IO index". The type is probably "up" or "down", to trigger when the button is pressed or released. And callback_function is the name of the function to be called every triggering.

| improve this answer | |
  • \$\begingroup\$ There's actually little reason to use an interrupt for this, and quite a lot of reason not to (bounce, etc). The one place an interrupt might really be useful would be to wake from sleep mode, but my (unconfirmed) sense is that unlike traditional/true MCU's an ESP8266 can't do that via an ordinary interrupt anyway. \$\endgroup\$ – Chris Stratton Sep 9 '19 at 5:21
  • \$\begingroup\$ Well, for a normal C code I agree, but the NodeMCU (in Lua) encourages the event driven paradigm, that's why polling is usually a bad way to get things done. You could create a timer event to poll and so on, but you could also place a low-pass filter on the pin to reduce bouncing... \$\endgroup\$ – jDAQ Sep 9 '19 at 12:33
  • \$\begingroup\$ Low pass filters do not work very well for debouncing. They can also cause problems with edge trigger circuits. A periodic time event actually is the best way to accomplish this. \$\endgroup\$ – Chris Stratton Sep 9 '19 at 13:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.