How to Use Seven Segment Display with Raspberry Pi: Simple Guide
seven segment display with a Raspberry Pi, connect its pins to the Pi's GPIO pins and control each segment by setting GPIO pins HIGH or LOW. Use a Python library like RPi.GPIO to write code that lights up segments to display numbers or letters.Syntax
To control a seven segment display, you set GPIO pins HIGH or LOW to turn on or off each segment labeled from 'a' to 'g'. Each segment corresponds to a pin on the display.
Basic steps:
- Import
RPi.GPIOand set GPIO mode. - Set GPIO pins connected to segments as outputs.
- Use
GPIO.output(pin, GPIO.HIGH)to light a segment. - Use
GPIO.output(pin, GPIO.LOW)to turn off a segment.
import RPi.GPIO as GPIO # Setup GPIO mode GPIO.setmode(GPIO.BCM) # Define pins connected to segments a-g segments = {'a': 2, 'b': 3, 'c': 4, 'd': 17, 'e': 27, 'f': 22, 'g': 10} # Setup pins as output for pin in segments.values(): GPIO.setup(pin, GPIO.OUT) # Turn on segment 'a' GPIO.output(segments['a'], GPIO.HIGH) # Turn off segment 'a' GPIO.output(segments['a'], GPIO.LOW) # Cleanup GPIO when done GPIO.cleanup()
Example
This example shows how to display the digit '2' on a common cathode seven segment display connected to Raspberry Pi GPIO pins using Python.
import RPi.GPIO as GPIO import time # Setup GPIO mode GPIO.setmode(GPIO.BCM) # Define pins for segments a-g segments = {'a': 2, 'b': 3, 'c': 4, 'd': 17, 'e': 27, 'f': 22, 'g': 10} # Setup pins as output for pin in segments.values(): GPIO.setup(pin, GPIO.OUT) # Digit 2 segments to turn on digit_2 = ['a', 'b', 'd', 'e', 'g'] # Turn on segments for digit 2 for segment in segments: if segment in digit_2: GPIO.output(segments[segment], GPIO.HIGH) else: GPIO.output(segments[segment], GPIO.LOW) print("Displaying digit 2 on seven segment display") time.sleep(5) # Keep display on for 5 seconds # Cleanup GPIO GPIO.cleanup()
Common Pitfalls
Wrong wiring: Connecting segments to wrong GPIO pins causes incorrect display.
Not using resistors: Always use current-limiting resistors to protect the display and Pi.
Wrong display type: Know if your display is common cathode or common anode; logic HIGH/LOW differs.
Forgetting GPIO cleanup: Not calling GPIO.cleanup() can cause pin conflicts on next run.
import RPi.GPIO as GPIO # Wrong: No GPIO setup or cleanup # GPIO.output(2, GPIO.HIGH) # This will cause error because pin not setup # Right way: GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.OUT) GPIO.output(2, GPIO.HIGH) GPIO.cleanup()
Quick Reference
Seven Segment Pins: a, b, c, d, e, f, g
GPIO Setup: Use GPIO.setmode(GPIO.BCM) and GPIO.setup(pin, GPIO.OUT)
Turn On Segment: GPIO.output(pin, GPIO.HIGH) (common cathode)
Turn Off Segment: GPIO.output(pin, GPIO.LOW)
Cleanup: Always call GPIO.cleanup() after use