# ============================================
# Practice 5: 7-Segment Display
# Intelligent IoT Design & Experiments - Week 1
# ============================================
# Learning Objectives:
# - Control multiple GPIO outputs
# - Map data using dictionaries
# - Understand the principle of 7-segment display
# ============================================
# 7-Segment Structure:
# ── a ──
# | |
# f b
# | |
# ── g ──
# | |
# e c
# | |
# ── d ── (dp)
# ============================================
from machine import Pin
import time
# --- Segment Pin Mapping (a~g, dp) ---
# a=GPIO2, b=GPIO4, c=GPIO5, d=GPIO6,
# e=GPIO7, f=GPIO8, g=GPIO9, dp=GPIO10
segment_pins = {
'a': Pin(2, Pin.OUT),
'b': Pin(4, Pin.OUT),
'c': Pin(5, Pin.OUT),
'd': Pin(6, Pin.OUT),
'e': Pin(7, Pin.OUT),
'f': Pin(8, Pin.OUT),
'g': Pin(9, Pin.OUT),
'dp': Pin(10, Pin.OUT),
}
# --- Number to Segment Mapping ---
# Order: (a, b, c, d, e, f, g) 1=ON, 0=OFF
DIGITS = {
0: (1, 1, 1, 1, 1, 1, 0),
1: (0, 1, 1, 0, 0, 0, 0),
2: (1, 1, 0, 1, 1, 0, 1),
3: (1, 1, 1, 1, 0, 0, 1),
4: (0, 1, 1, 0, 0, 1, 1),
5: (1, 0, 1, 1, 0, 1, 1),
6: (1, 0, 1, 1, 1, 1, 1),
7: (1, 1, 1, 0, 0, 0, 0),
8: (1, 1, 1, 1, 1, 1, 1),
9: (1, 1, 1, 1, 0, 1, 1),
}
# List of segment names (for order mapping)
SEG_ORDER = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
def display_digit(num):
"""Display numbers 0-9 on 7-segment"""
if num not in DIGITS:
# Turn off everything if not a number
for seg in segment_pins.values():
seg.value(0)
return
pattern = DIGITS[num]
for i, seg_name in enumerate(SEG_ORDER):
segment_pins[seg_name].value(0 if pattern[i] else 1)
print(f"Display: {num}")
def all_off():
"""Turn off all segments"""
for seg in segment_pins.values():
seg.value(0)
# --- Main: 0-9 Counter ---
print("=== Starting 7-Segment Display ===")
print("Displaying numbers 0 to 9 in sequence.")
print()
while True:
for digit in range(10):
display_digit(digit)
time.sleep(1)
# Blink effect before restarting
for _ in range(3):
all_off()
time.sleep(0.2)
display_digit(0)
time.sleep(0.2)
all_off()
time.sleep(0.5)
# ============================================
# 💡 Practice Exercises:
# 1) Map alphabets A, b, C, d, E, F to display hexadecimal.
# 2) Create a clock effect using the decimal point (dp) as a blinking dot.
# 3) Implement a counter where buttons increase or decrease the number.
# ============================================