The objective of this experiment is to interface a common cathode 7-segment display with a Raspberry Pi Pico, and control the number shown on the display using a single push button. Each time the button is pressed, the display should increment the number from 1 up to 9. Once 9 is reached, the next button press should cycle it back to 1. This experiment demonstrates the use of digital output for segment control, digital input for reading a switch, and basic logic to track and update numeric values on hardware displays.
Buy Basic Raspberry Pi Pico Kit
Items Required:
- Raspberry Pi Pico board
- Common cathode 7-segment display
- One push button switch
- Breadboard
- Jumper wires
- USB Micro B cable for Pico
- Computer with Thonny IDE (or any MicroPython environment)
Connections:
7-Segment Display (Common Cathode):
- Segment a → GPIO 0
- Segment b → GPIO 1
- Segment c → GPIO 2
- Segment d → GPIO 3
- Segment e → GPIO 4
- Segment f → GPIO 6
- Segment g → GPIO 7
- Common cathode pins → GND (both cathode pins if available)
- · One terminal of the push button → GPIO 5
- · Other terminal of the push button → GND


Code:
from machine import Pin
import time
# Define segment GPIOs for a to g
segments = [
Pin(0, Pin.OUT), # a
Pin(1, Pin.OUT), # b
Pin(2, Pin.OUT), # c
Pin(3, Pin.OUT), # d
Pin(4, Pin.OUT), # e
Pin(6, Pin.OUT), # f
Pin(7, Pin.OUT) # g
]
# Define digit to segment mapping for common cathode
digit_segments = [
# a b c d e f g
[0,1,1,0,0,0,0], # 1
[1,1,0,1,1,0,1], # 2
[1,1,1,1,0,0,1], # 3
[0,1,1,0,0,1,1], # 4
[1,0,1,1,0,1,1], # 5
[1,0,1,1,1,1,1], # 6
[1,1,1,0,0,0,0], # 7
[1,1,1,1,1,1,1], # 8
[1,1,1,1,0,1,1] # 9
]
# Push button pin
button = Pin(5, Pin.IN, Pin.PULL_UP)
count = 0
def display_digit(n):
if 1 <= n <= 9:
pattern = digit_segments[n - 1]
for i in range(7):
segments[i].value(pattern[i])
else:
# Turn off all segments
for seg in segments:
seg.value(0)
# Start with display off
display_digit(0)
# Main loop
while True:
if button.value() == 0: # Button pressed (active low)
count += 1
if count > 9:
count = 1
display_digit(count)
time.sleep(0.3) # Debounce and prevent multiple counts
# Wait for release
while button.value() == 0:
time.sleep(0.01)
time.sleep(0.01)
Result:
When the Raspberry Pi Pico is powered on, the 7-segment display remains off initially. On the first button press, the number “1” appears on the display. Each subsequent press increments the number shown, going from 1 to 9. After 9, pressing the button again will wrap the count back to 1, and the cycle continues.