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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# digital_input.py

# Raspberry Pi Pico - Digital Input demo

# Read a digital I/O line, drive the onboard LED, and print messages to the
# serial console only when the input state changes.

import board
import time
from digitalio import DigitalInOut, Direction, Pull

#---------------------------------------------------------------
# Set up the hardware: script equivalent to Arduino setup()

# Set up built-in green LED for output.
led = DigitalInOut(board.LED)  # GP25
led.direction = Direction.OUTPUT

# Set up a digital input on GP15, which is physically pin 20 at one corner of the board.
# E.g., this may be attached to a switch or photointerrupter with associated pullup resistor.
switch = DigitalInOut(board.GP15)
switch.direction = Direction.INPUT

#---------------------------------------------------------------
# Run the main loop: script equivalent to Arduino loop()

# The following logic detects input transitions using a state machine with two
# possible states.  The state index reflects the current estimated state of the
# input.
state_index = False

while True:
    if state_index is False:
        if switch.value is True:
            led.value = True
            state_index = True
            print("On")

    elif state_index is True:
        if switch.value is False:
            led.value = False
            state_index = False
            print("Off")