Digital Input/Output Examples - Raspberry Pi Pico

The following short Python programs will demonstrate essential operation of the Raspberry Pi Pico board. These assume one or more binary input or output circuits are externally attached. Each can be run by copying the program into code.py on the CIRCUITPY drive offered by the board. The text can be pasted directly from this page, or each file can be downloaded from the CircuitPython sample code folder on this site.

Related Pages

Digital Input

Direct download: digital_input.py.

 1# digital_input.py
 2
 3# Raspberry Pi Pico - Digital Input demo
 4
 5# Read a digital I/O line, drive the onboard LED, and print messages to the
 6# serial console only when the input state changes.
 7
 8import board
 9import time
10from digitalio import DigitalInOut, Direction, Pull
11
12#---------------------------------------------------------------
13# Set up the hardware: script equivalent to Arduino setup()
14
15# Set up built-in green LED for output.
16led = DigitalInOut(board.LED)  # GP25
17led.direction = Direction.OUTPUT
18
19# Set up a digital input on GP15, which is physically pin 20 at one corner of the board.
20# E.g., this may be attached to a switch or photointerrupter with associated pullup resistor.
21switch = DigitalInOut(board.GP15)
22switch.direction = Direction.INPUT
23
24#---------------------------------------------------------------
25# Run the main loop: script equivalent to Arduino loop()
26
27# The following logic detects input transitions using a state machine with two
28# possible states.  The state index reflects the current estimated state of the
29# input.
30state_index = False
31
32while True:
33    if state_index is False:
34        if switch.value is True:
35            led.value = True
36            state_index = True
37            print("On")
38
39    elif state_index is True:
40        if switch.value is False:
41            led.value = False
42            state_index = False
43            print("Off")