Skip to content

LED with Push Button

Lolin1LED

Summary

This is another LED exercise using internal and external components. For the first part of the tutorial we will be using the on-board internal LED. If you remember the second tutorial with the LED this one will be similar. The difference is that we will be using a push button to light up the LED this time.

Requirements

  • 1 x Lolin D1 Mini Pro board
  • 1 x Micro USB
  • 1 x Breadboard
  • 1 x LED
  • 2 x Resistor 1k ohm
  • 1 x Push Button
  • 4 x cables

On-board LED with push button

Connect your board to your computer

This step should be easy if you completed the first tutorial.

  • Connect the one end of your micro usb on your board and the other end to your computer.

  • Open PuTTY and select Serial connection type.

  • Use the appropriate Serial Line COM5 (same you did on Tutorial 1, if you don't remember it you can find it through device manager) and speed 115200 and click open.

Ports

Putty

Create the following circuit

LED button

  • Use the following code
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    import time
    from machine import Pin
    led = Pin(2, Pin.OUT)
    button = Pin(14, Pin.IN, Pin.PULL_UP)
    while True:
        if not button.value():
            led(not led())
            time.sleep(0.3)
            while not button():
                pass
    

Now when you press the button the on-board LED will light up and when you press it again it will switch off.

External LED with push button

Now create the following circuit. Remember to remove the micro usb when connecting components to avoid damaging them.

Note that Pin named D6 on the circuit is number 12 on LOLIN and pin named D5 is the pin number 14.

External LED button

We will be using the same code as before with one difference. The pin 2 we used for the LED before, it is now changed it to 12 which is the pin we are now using for the external LED.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    import time
    from machine import Pin
    led = Pin(12, Pin.OUT)
    button = Pin(14, Pin.IN, Pin.PULL_UP)
    while True:
        if not button.value():
            led(not led())
            time.sleep(0.3)
            while not button():
                pass

Now when you press the push button the external LED will light up, and when you press it again the LED will switch off.

This is the end of Tutorial 4, you should now be able to make the external or built-in LED light up.