ESP8266 Access GPIO Using Micropython

In this post I’ll be writing about accessing GPIO ports on ESP8266.

Module machine contains the apis for the GPIO on ESP8266.

import machine
pin = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP)

To use a GPIO we need to configure it as either input or output. In the above example machine.Pin.IN configures the GPIO pin as an input, meaning you can connect a button like the one shown below to it.

The machine.Pin.PULL_UP indicates that, the input pin will give 1 when the button is not pressed, and you will get the output 0 when button is pressed.

Now when you need to use the pin as an output pin, you need to

pin = machine.Pin(2, machine.Pin.OUT)

This will make the pin an output pin.

you can control the output of the pin by using Pin.on() and Pin.off() methods.

>>> import machine
>>> pin = machine.Pin(2, machine.Pin.OUT)
>>> dir(pin)
['__class__', 'IN', 'IRQ_FALLING', 'IRQ_RISING', 'OPEN_DRAIN', 'OUT', 'PULL_UP', 'init', 'irq', 'off', 'on', 'value']
>>> 

Following is the program to turn on an led when the button is pressed.

import machine

inputPin  = machine.Pin(15, machine.Pin.IN)
outputPin = machine.Pin(2, machine.pin.OUT)

def main():
    while True:
        if inputPin.value() == 1:
            outputPin.on()
        else:
            outputPin.off()

main()

In the next post I’ll be writing about sending data from and to ESP8266 using MQTT.