micropython-entradas-y-salidas-digitales

Digital Inputs and Outputs with GPIO in MicroPython

  • 3 min

In this tutorial, we are going to see how to use 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, GPIOs are managed through the Pin class, which provides us with the 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
Copied!

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

Digital Output

Let’s start by seeing how to use a pin as an output. For this

  1. We use the Pin method
  2. We specify the pin number (or the name, if it has one)
  3. We use the 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
Copied!

In this example,

  • We have declared the board’s integrated “LED” pin as an output.
  • We have declared pin 6 as an output.

Now we can use the value() method or on() and off() 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()
Copied!

Digital Input

Now let’s see how to use a pin as an input. It’s basically very similar,

  1. We also use the Pin method
  2. We specify the pin number (or 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
Copied!

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
Copied!

The value() method, called without parameters.

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

Practical Examples