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
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
- We use the
Pinmethod - We specify the pin number (or the name, if it has one)
- 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
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()
For simplicity, I’m using the board’s integrated LED in the example. If you want to use an external LED, you will need to connect it with its resistor, as we saw in the post,
Digital Input
Now let’s see how to use a pin as an input. It’s basically very similar,
- We also use the
Pinmethod - We specify the pin number (or name)
- 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
1if the pin is HIGH - Returns
0if the pin is LOW
Practical Examples
Blinking an LED
Our beloved “blink”, an example that makes an LED connected to pin 2 blink.
from machine import Pin
import time
led = Pin(2, Pin.OUT) # Configures pin 2 as an output
while True:
led.on() # Turns on the LED
time.sleep(1) # Waits for 1 second
led.off() # Turns off the LED
time.sleep(1) # Waits for 1 second
This code makes the LED blink every second.
