MicroPython on NodeMCU with Button and LED

Pins

  • I am using the same NodeMCU board to test the DHT11 sensor as well.
  • The button, DHT11, and LED each have a data pin.
  • The ground is common amongst all electronic pieces.

Control the LED

  • The short wire of the LED is the negative connection.
  • The connectors of the LED are important, ensure that the short wire is connected to ground.
  • The resistor ensures that the LED does not get overloaded.
  • The LED connects to NodeMCU data pin #5 (D5) which is GPIO Pin ID #14.
from machine import Pin

led = Pin(14, Pin.OUT)

# pin value 1 = LED on
# pin value 0 = LED off

## turn LED off
led.value(0)

## turn LED on
led.value(1)


ledStatus = "off"
if (led.value() == 1):
  ledStatus = "on"

print( "LED Value: " +  ledStatus)

Read the status of the Button

  • When the button is up (not depressed) the value is 1.
  • The LED connects to NodeMCU data pin #2 (D2) which is GPIO Pin ID #4.
from machine import Pin

button = Pin(4, Pin.IN, Pin.PULL_UP)

buttonStatus = "up"
if (button.value() == 0):
  buttonStatus = "down"

print( "Button Status: " +  buttonStatus)

Use the button to control the LED

  • When the button is pressed, the LED status is changed.
  • If the LED was turned off, it is turned on.
  • If the LED was turned on, it is turned off.
from machine import Pin
from time    import sleep

led    = Pin(14, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)

def led_toggle():
  led.value(not led.value())

while True:
  if not button.value():
    led_toggle()
    sleep(.5)

Use the button to control the LED and display the current temperature

  • Print the temperature to stdout on the console.
  • When the button is pressed down, light the light up.
  • When the button is up, turn off the light.
  • The temperature can only be polled every 2 seconds so build a 2 second sleep in to the code.
    Ultimately this method would fail outside of a test as the light could be left on after the button was depressed.
import dht
from machine import Pin
from time    import sleep

led    = Pin(14, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)
d      = dht.DHT11(Pin(2))

while True:
  if not button.value():
    led.value(1)
    d.measure()
    c      = d.temperature()
    h      = d.humidity()
    f      = (c * 1.8 + 32)
    print( "Temp is " + str(c) + "C (" + str(f) + "F) and RH is " + str(h) )
    sleep(2)
  else:
    led.value(0)
categories: micropython | esp8266 | nodemcu |