Digital Output

Let's blink a LED!

Here's the bread board layout. The resistor can be something around 1kOhm. We don't need to make the LED super bright.

First, let's do things interactively so you can see how it all works one line at a time. Start by launching Python:

Download: file
python3

Then, at the Python >>> prompt, enter the following to import the needed modules:

Download: file
import board
import digitalio

Next we'll create our LED digital pin and set the mode to output:

Download: file
led = digitalio.DigitalInOut(board.G0)
led.direction = digitalio.Direction.OUTPUT

And that should be it. You should be able to turn ON the LED with:

Download: file
led.value = True

And turn it OFF with:

Download: file
led.value = False

And here's a complete blink program you can run to make the LED blink forever.

Download: file
import time
import board
import digitalio
     
led = digitalio.DigitalInOut(board.G0)
led.direction = digitalio.Direction.OUTPUT
     
while True:
    led.value = True
    time.sleep(0.5)
    led.value = False
    time.sleep(0.5)

Save it as something like blink.py and then you can run it with:

Download: file
python3 blink.py

The LED should blink on and off.

Digital Input

Let's read a button!

Here's the bread board layout. Use something like a 10kOhm resistor.

The GPIO pins do not have internal pull-up or pull-down support! If you need pull resistors, add them externally as shown here!

We'll do this interactively also. So launch python:

Download: file
python3

Then, at the Python >>> prompt, enter the following to import the needed modules:

Download: file
import board
import digitalio

And now we create our button digital pin and set it to input.

Download: file
button = digitalio.DigitalInOut(board.G0)
button.direction = digitalio.Direction.INPUT

And that's it. To read the current state of the button use:

Download: file
button.value

This will return False when the button is not pressed and True when it is pressed.

Digtal Input and Output

Ok, let's put those two together and make the button turn on the LED. So we'll use two digital pins - one will be an input (button) and one will be an output (LED).

Here's the bread board layout.

And here's the code.

Download: file
import board
import digitalio

led = digitalio.DigitalInOut(board.G0)
led.direction = digitalio.Direction.OUTPUT

button = digitalio.DigitalInOut(board.G1)
button.direction = digitalio.Direction.INPUT

while True:
    led.value = button.value

Save that to a file with a name like button_and_led.py and then you can run it with:

Download: file
python3 button_and_led.py

and the button should turn on the LED when pressed.

This guide was first published on Dec 22, 2019. It was last updated on 2020-02-07 13:24:40 -0500. This page (GPIO) was last updated on Feb 15, 2020.