micropython-entradas-y-salidas-digitales

Digital Inputs and Outputs with GPIO in MicroPython

  • 3 min

In this tutorial, we will see how to use the GPIO pins in MicroPython, and how to use them as digital inputs and outputs.

GPIO (General Purpose Input/Output) are digital pins on a development board that can be configured as inputs or outputs.

  • Output: A pin configured as an output can control an external device (like an LED or a relay).
  • Input: A pin configured as an input can read a voltage reference.

These pins allow the board to interact with external devices, such as LEDs, buttons, sensors, and actuators.

Configuring a GPIO Pin

In MicroPython, GPIO are handled through the Pin class, which provides us with methods to configure and control the pins.

To use a GPIO pin in MicroPython, we first need to import the Pin class from the machine module.

from machine import Pin

Once imported, we can configure the pin as an input or output, and use the functions through the Pin object.

Digital Output

Let’s start by looking at how to use a pin as an output. To do this,

  1. We use the Pin method
  2. Specify the pin number (or the name, if it has one)
  3. Use as mode (Pin.OUT).

Let’s see it with an example.

led = Pin("LED", Pin.OUT)  # Configures the LED as an output

another_led = Pin(6, Pin.OUT)  # Configures pin 6

In this example,

  • We have declared the built-in pin on the board “LED” as an output.
  • We have declared pin 6 as an output.

Now we can use the value() or on() and off() methods to control the state of the pin.

led.on()      # Turns on the LED
led.value(1)  # is the same as on()

led.off()     # Turns off the LED
led.value(0)  # which is the same as off()

Digital Input

Now let’s see how to use a pin as an input. Basically, it is very similar,

  1. We also use the Pin method
  2. Specify the pin number (or the name)
  3. This time we use the mode Pin.IN

Let’s see it with an example.

my_input = Pin(4, Pin.IN)  # Configures pin 4 as an input

Once we have the pin configured, we can use the value() method to read the state of the pin.

state = my_input.value()  # Reads the state of the pin

The value() method, called without parameters.

  • Returns 1 if the pin is HIGH
  • Returns 0 if the pin is LOW

Practical Examples