Jul 20

Toggle LED on/off by pressing a button - NodeMCU - ESP8266

Category: Design,electronics   — Published by goeszen on July 20, 2017 at 10:41 pm

Elaborating on a previous example/post we here combine toggling the on-board LED by pressing a push-button connected to the ESP8266 NodeMCU board.

This video demonstrates the result of below code and wire-up:

Wire-up the hardware according to the layout shown in the button post:

Then upload the following lua script as init.lua to your board:

-- Config
local button_pin = 7
local count = 0;

local pin = 4            --> GPIO2
local value = gpio.LOW

-- init GPIO pin properly
-- some hardware might not need the "gpio.PULLUP" part, mine does
gpio.mode(button_pin, gpio.INT, gpio.PULLUP)

-- Function toggles LED state
function toggleLED ()
   if value == gpio.LOW
        value = gpio.HIGH
       value = gpio.LOW

    gpio.write(pin, value)

-- define a callback function named "pin_cb", short for "pin callback"
function pin_cb()
	count = count + 1
	print("Pressed ".. count)

gpio.mode(pin, gpio.OUTPUT)
gpio.write(pin, value)

-- register a button event
-- that means, what's registered here is executed upon button event "up"
gpio.trig(button_pin, "up", pin_cb)

... and you're ready to go. Press the button and the LED will light up or go dark. A basic ESP8266 script. Happy tinkering!

Related posts:
Simple button on NodeMCU - ESP8266
Blink the internal LED - ESP8266


I'm tinkering here with a NodeMCU ESP8266 board.
I'm using the ESP8266 Java IDE ESPlorer.
The firmware is version 0.9.6 build 20150704 powered by Lua 5.1.4

Leave a Reply