Chapter 18 74HC595 & 7-segment display.
78
79
80
81
82
83
84
85
86
87
89
g lobal t
GPIO. cleanup()
t. cancel() #cancel the timer
if __name__ == '__main__': # Program starting from here
p rint ('Program is starting...' )
setup()
try:
loop()
e xcept KeyboardInterrupt:
destroy()
First, define the pin of 74HC595 and 7-segment display common end, character encoding and a variable
"counter" to be displayed counter.
dataPin = 18 #DS Pin of 74HC595(Pin14)
latchPin = 16 #ST_CP Pin of 74HC595(Pin12)
clockPin = 12 #CH_CP Pin of 74HC595(Pin11)
num = (0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90)
digitPin = ( 11, 13,15,19) # Define the pin of 7-segment display common end
counter = 0 # Variable counter, the number will be displayed by 7-segment display
Subfunction selectDigit (digit) function is used to open one of the 7-segment display and close the other 7-
segment display, where the parameter digit value can be 1,2,4,8. Using "|" can open a number of 7-segment
display.
def selectDigit(digit): #Open one of the 7-segment display and close the remaining three,
the parameter digit is optional for 1,2,4,8
GPIO. output(digitPin[0],GPIO.LOW if ((digit&0x08) == 0x08) else GPIO.HIGH)
GPIO. output(digitPin[1],GPIO.LOW if ((digit&0x04) == 0x04) else GPIO.HIGH)
GPIO. output(digitPin[2],GPIO.LOW if ((digit&0x02) == 0x02) else GPIO.HIGH)
GPIO. output(digitPin[3],GPIO.LOW if ((digit&0x01) == 0x01) else GPIO.HIGH)
Subfunction outData (data) is used to make the 74HC595 output a 8-bit data immediately.
def outData(data): #function used to output data for 74HC595
GPIO. output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,data)
GPIO. output(latchPin,GPIO.HIGH)
Subfunction display (dec) is used to make 4-Digit 7-segment display a 4-bit integer. First open the common
end of first 7-segment display and close to the other three, at this time, it can be used as 1-Digit 7-segment
display. The first is used for displaying single digit of "dec", the second for tens digit, third for hundreds digit
and fourth for thousands digit respectively. Each digit will be displayed for a period of time through using
delay (). The time in this code is set very short, so you will see different digit is in a mess. If the time is set long
enough, you will see that every digit is display independent.
def display(dec): #display function for 7-segment display
outData(0xff) #eliminate residual display
selectDigit(0x01) #Select the first, and display the single digit
outData(num[dec%10])
time. sleep(0.003) #display duration