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.
If you want to learn more, check out,
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,
- We use the
Pin
method - Specify the pin number (or the name, if it has one)
- 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()
For simplicity, I am using the built-in LED on the board 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. Basically, it is very similar,
- We also use the
Pin
method - Specify the pin number (or the 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
1
if the pin is HIGH - Returns
0
if the pin is LOW
Practical Examples
LED Blinking
Our dear “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.