How to control a 4 digit 7 Segment Display from Raspberry PI with Python
How to control a 4 digit 7 Segment Display from Raspberry PI with Python
Some links in this post may be affiliate links. We may get paid if you buy something or
take an action after clicking one of these, but without addictional costs for you
compared to direct buying.
How to control a 4 digit 7 Segment Display from
Raspberry PI with Python
13 Comments / Python, RPI Computers / By peppe8o
4 digit 7 segment display is widely known and used in clock, simple screens and low
cost number displaying. Raspberry PI can directly manage it by using proper GPIO
connections and a few lines of python code
It is used within a wide number application, usually to
diplay time.
When using 4-digit 7-segment display, please notice that if it is common anode, the
common anode pin connects to the power source; if it is common cathode, the
common cathode pin connects to the GND. This guide is based on cathode one, nut
anode works with the same code by inverting digit selection logic.
Followin picture shows also the pinout for the cathodic 4 digit display I’m going to
use:
In this article we’ll control our 4 Digit 7 segment display from a Raspberry PI Zero W.
This article applies also to newer Raspberry PI boards.
What We Need
As usual, I suggest adding from now to your favourite e-commerce shopping cart all
the needed hardware, so that at the end you will be able to evaluate overall costs and
:
decide if to continue with the project or remove them from the shopping cart. So,
hardware will be only:
Raspberry PI Zero W (including proper power supply or using a smartphone micro usb
charger with at least 3A) or newer Raspberry PI Board
high speed micro SD card (at least 16 GB, at least class 10)
Dupont Wiring
Solderless breadboard
a 4 digit 7 segment display
4x resistors (100 Ohm used)
Step-by-Step Procedure
Wiring Diagram
A 11 18 24
B 7 22 25
C 4 24 8
D 2 26 7
E 1 28 1
F 10 32 12
G 5 36 16
DP 3 38 20
:
DIGIT 1 12 8 14
DIGIT 2 9 10 15
DIGIT 3 8 12 18
DIGIT 4 6 16 23
Start with OS installation using Install Raspberry PI OS Lite guide. This guide can be
also used with Raspberry PI OS Desktop installation.
RPI.GPIO should be already installed (otherwise, you can get it installed with the
command “sudo apt install python3-rpi.gpio”).
wget https://peppe8o.com/download/python/seg4DigitDisplay.py
Script Usage
python3 seg4DigitDisplay.py
This variable can be set with four numbers and one dot or no dot after each number.
A space will deploy a powered off digit corresponding to its position. Please find
below some valid examples:
12.34
1.23.4
1234.
1 2.3 (there is a space between “1” and “2”)
1.2 3. (there is a space between “2” and “3”)
123. (there is a space before “1”)
1.2.3.4.
1234
:
To stop the script, simply press CTRL+C. This will execute a GPIO cleanup closing all
GPIOs.
Script explanation
Delay is the time every single digit stays on. So, it also depends on the refresh rate for
the overall display. This is an important variable. A too low delay means that
Raspberry PI could not be able to disable/enable GPIOs so fast, thus resulting in all
segments in all digits appearing on. A too high delay means that refresh rate is
affected, resulting in a blinking effect for display digits (with the persistence of vision
resulting compromised). Also, resistors affect these results. With 100ohm resistors, I
reached a good result on 0.005 seconds delay.
The following section defines what Raspberry PI pins we are going to use. We will use
BCM naming convention. Please refer to Raspberry PI Pinout for physical to BCM
relations
selDigit = [14,15,18,23]
# Digits: 1, 2, 3, 4
digitDP = 20
#DOT = GPIO 20
Warnings are disabled because this script will leave the display active after execution.
An array is prepared to manage easily segments activation for each single number (so
that arrSeg[0] shows 0, arrSeg[1] shows 1, etc):
arrSeg = [[1,1,1,1,1,1,0],\
[0,1,1,0,0,0,0],\
[1,1,0,1,1,0,1],\
[1,1,1,1,0,0,1],\
[0,1,1,0,0,1,1],\
[1,0,1,1,0,1,1],\
[1,0,1,1,1,1,1],\
[1,1,1,0,0,0,0],\
[1,1,1,1,1,1,1],\
[1,1,1,1,0,1,1]]
Then the two main functions come. As you can remember, we defined what to display
as a string in toDisplay variable. spliToDisplay function splits this string in an array of
4 elements so that each element is a simple number (or space). Also, dots are added
to the element that the dot is following.
With an array so composed, the showDsiplay function takes charge to display all 4
:
digits. This uses a for cycle with 4 steps. Each step enables a digit by putting its
selector to 0 (LOW). This is because we are using a cathode Display.
def showDisplay(digit):
for i in range(0, 4): #loop on 4 digits selectors (from 0 to 3
included)
sel = [1,1,1,1]
sel[i] = 0
GPIO.output(selDigit, sel) # activates selected digit
if digit[i].replace(".", "") == " ": # space disables digit
GPIO.output(display_list,0)
continue
numDisplay = int(digit[i].replace(".", ""))
GPIO.output(display_list, arrSeg[numDisplay]) # segments are
activated according to digit mapping
if digit[i].count(".") == 1:
GPIO.output(digitDP,1)
else:
GPIO.output(digitDP,0)
time.sleep(delay)
With anode displays modify the two rows according to the following:
sel = [0,0,0,0]
sel[i] = 1
Finally, the main loop is an infinite number of recalls to previously defined functions in
pipe.
try:
while True:
showDisplay(splitToDisplay(toDisplay))
except KeyboardInterrupt:
print('interrupted!')
GPIO.cleanup()
sys.exit()
!!!!!
Average rating 3.3 / 5. Vote count: 9
Previous Post
Next Post
Hey,
I modified your code a bit to get it worked for me, basically it is quite similar to what
you have achieved so far, but there is some changes in the way of displaying
numbers.
I appreciate your efforts to make such nice tutorials.
import sys, os
import RPi.GPIO as GPIO
import time
import random
#fpid = os.fork()
#if fpid!=0:
to_display = ‘12,25’
GPIO.setmode (GPIO.BCM)
GPIO.setwarnings(False)
display_list = [17,27,22,10,9,11,6] #
# display list ref: A, B, C, D, E, F, G
for pin in display_list:
GPIO.setup(pin,GPIO.OUT) # set pins for each segement
:
# digits 1, 2, 3,4
set_digit = [26,8,19,7] #23=29
for digit in set_digit:
GPIO.setup(digit,GPIO.OUT) # set pins for digit selector
digit_dot = 16
# dot GPIO port
GPIO.setup(digit_dot, GPIO.OUT)
GPIO.setwarnings(True)
# A, B, C, D,E,F,G
arrSeg = [[0,0,0,0,0,0,1],\
[1,0,0,1,1,1,1],\
[0,0,1,0,0,1,0],\
[0,0,0,0,1,1,0],\
[1,0,0,1,1,0,0],\
[0,1,0,0,1,0,0],\
[0,1,0,0,0,0,0],\
[0,0,0,1,1,1,1],\
[0,0,0,0,0,0,0],\
[0,0,0,0,1,0,0]]
GPIO.output(set_digit,sel_digit[i])
GPIO.output(display_list,arrSeg[int(new_num[i])])
# activate decimal digit
if num[i+1] == ‘.’:
GPIO.output(digit_dot,0)
else:
GPIO.output(digit_dot,1)
time.sleep(.0001)
:
# integer number
else:
for i in range(0,4):
sel_digit = [[1, 0, 0, 0],\
[0, 1, 0, 0],\
[0, 0, 1, 0],\
[0, 0, 0, 1]]
GPIO.output(set_digit,sel_digit[i])
GPIO.output(display_list,arrSeg[int(num[i])])
time.sleep(.0001)
try:
time_end = time.time()+2 # time.time() time elapsed since 1970 in seconds
except KeyboardInterrupt:
print('interrupted!')
finally:
GPIO.cleanup()
sys.exit()
Best wishes,
:
aVral
Reply
PEPPE8O
4TH JUNE 2020 AT 9:10 AM
Reply
ETHAN
7TH MARCH 2021 AT 1:41 AM
Is there a way to make it display the current time? I’m new to python.
Reply
PEPPE8O
7TH MARCH 2021 AT 9:08 AM
Hi Ethan.
Try changing following code string:
showDisplay(splitToDisplay(toDisplay))
with following one:
showDisplay(splitToDisplay(time.strftime("%H.%M")))
This uses “strftime” function from time library (already imported) to get current hour
:
and minute into a string format. Remember to maintain same indentantion.
Please, let me know if this works.
Reply
FRANKVELLA300
28TH APRIL 2021 AT 11:31 PM
Reply
MICAH
2ND JANUARY 2022 AT 3:15 PM
I have a 3 digit display, which there doesn’t seem to be much documentation on it… Is
it fairly easy to use this code for that?
Reply
PEPPE8O
3RD JANUARY 2022 AT 10:10 AM
Hi Micah. Do you mean that you have a 3-digit display or are you meaning 3x 4-digit
displays?
Reply
:
JASON
29TH JANUARY 2022 AT 12:54 AM
I want to increment the display number by pressing a button. So I added some code
to your while loop. It almost works. It will only display the last digit of the
numberToDisplay. So when I get to 12, it only displays a 2. And 113, only displays a 3.
Any idea why?
Thank you
showDisplay(splitToDisplay(toDisplay))
button.wait_for_press()
#increment
numberToDisplay = numberToDisplay +1
button.wait_for_release()
if numberToDisplay < 10:
toDisplay = " " + str(numberToDisplay)
elif numberToDisplay < 100:
toDisplay = " " + str(numberToDisplay)
elif numberToDisplay < 1000:
toDisplay = " " + str(numberToDisplay)
else:
toDisplay = "" + str(numberToDisplay)
print(toDisplay)
Reply
:
PEPPE8O
29TH JANUARY 2022 AT 12:54 PM
Hi Jason,
comments on HTML pages may not save the right number of consecutive spaces,
so I suppose that your code adds 3 spaces before the “str(numberToDisplay)” in the
first IF statement, 2 on the second and 1 on the third.
For each numberToDisplay value, do you always see only the last digit powered on?
What if you start from numberToDisplay=100?
The very first check I would make will be on cabling.
Reply
NICOLAUS
19TH FEBRUARY 2022 AT 12:31 PM
I’ve followed the plan closely but when I run it my display says 4.5.9.9.
I’m new to Python
Reply
PEPPE8O
19TH FEBRUARY 2022 AT 12:35 PM
Hi Nicolaus,
when the showed number is different from expected it probably means that some
cables are not connected to the right PIN. Please double check wiring
:
Reply
TECHGIRLNEXTDOOR
27TH OCTOBER 2022 AT 5:53 PM
Hey! This tutorial was great! Can I know how I can modify the code to display
numbers from 1-0 and alphabet from A-Z? As well as maybe a small message like
‘hello’ or something in a loop? I would very much appreciate your response!
Reply
PEPPE8O
11TH NOVEMBER 2022 AT 8:05 AM
Reply
Leave a Comment
Your email address will not be published. Required fields are marked *
:
Type here..
Name*
Email*
Website
Post Comment »
Subscribe to my Newsletter