Pushing NodeMcu’s buttons

After getting started with NodeMcu and figuring out the basics of using the GPIO pins for output, the obvious next step was to give input a go. So I set myself another challenge: to wire up a button which lit up an LED on another GPIO pin.

The code

The first thing I did was to head back to the NodeMcu documentation to check out how to set the pin mode to input. Seeing a lot more options than the simple “INPUT” or “OUTPUT” I was expecting, I chose the interrupt mode. This would allow me to use the button as a “trigger”, which could then call another function to change the state of my LED.

The last optional argument was also interesting, giving me the option of using an internal weak pull-up. I had no idea what this was referring too, however after watching a couple of YouTube videos I managed to get my head around it. Would also recommend this site here which has an easy-to-understand description. Basically it stops the pin from “floating” (being in a state of not on or off, just floating) as well as preventing shorts. It involves keeping the pin at a high voltage while the button is off, and dropping the voltage when the button is pressed. With this built in (or so I hope from the word “internal” in the description) it allows me to make a much simpler circuit, so it got included.

Once I had my input pin mode set correctly, I set my other pin to output (for my LED), and set up my interrupt function. I set it to trigger on both the increase and decrease in current, allowing me to turn on the LED on the way up, and off on the way down.

gpio.mode(1, gpio.INT, gpio.PULLUP)
gpio.mode(2, gpio.OUTPUT)

gpio.trig(1, "both", function(level)
    gpio.write(2, 1-level)

The hardware

I used the same setup for my LED as I did in my first project. D2 to the LED, through a resistor and out to ground.

Button was equally simple, using the internal weak pull-up allowed me to go straight from D1, to the button, to ground.

The result

Now I know how to get connected to this little device and work the GPIOs, this challenge was far more straightforward than my previous attempt at electronics. Pressing the button kicks off the interrupt successfully, turning on my LED, and releasing the button turns it back off. At least some of the time. Occasionally it seems to get stuck and I’m not too sure why. Could be the order or speed of the interrupts? A mistake in my circuit? I’m not sure. Pressing the button again seems to solve the problem though. It will do for now.