Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
i am a noob and need help
#1
so i bought a raspberry pi kit and one of the projects was with a 7-segment display and i need help under standing the code. in particular the dats section as well as writeOneByte(val): section

import RPi.GPIO as GPIO
import time

pins = [11,12,13,15,16,18,22,7]
dats = [0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x80]

def setup():
	GPIO.setmode(GPIO.BOARD)
	for pin in pins:
		GPIO.setup(pin, GPIO.OUT)   # Set pin mode as output
		GPIO.output(pin, GPIO.LOW)

def writeOneByte(val):
	GPIO.output(11, val & (0x01 << 0))  
	GPIO.output(12, val & (0x01 << 1))  
	GPIO.output(13, val & (0x01 << 2))  
	GPIO.output(15, val & (0x01 << 3))  
	GPIO.output(16, val & (0x01 << 4))  
	GPIO.output(18, val & (0x01 << 5))  
	GPIO.output(22, val & (0x01 << 6))  
	GPIO.output(7,  val & (0x01 << 7)) 

def loop():
	while True:
		for dat in dats:
			writeOneByte(dat)
			time.sleep(0.5)

def destroy():
	for pin in pins:
		GPIO.output(pin, GPIO.LOW)
	GPIO.cleanup()             # Release resource

if __name__ == '__main__':     # Program start from here
	setup()
	try:
		loop()
	except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
		destroy()[/b]
Reply
#2
I don't use such code, but it seems relatively easy to understand. Obviously the segments are numbered 11,12,13,15,16,18,22,7 (I guess 7 is the dot). A state of the 7-segment display is represented by a small integer < 256 such as 0x5b
>>> val = 0x5b
>>> val                                                                                      
91
>>> bin(val)                                                                                 
'0b1011011'
The eight bits of the value's binary representation give the desired state of the display. Reading 1011011 from right to left, we see that segments 11 and 12 need to be On, 13 need to be Off, 15 and 16 need to be On, 18 Off, 22 On and 7 Off (missing binary digits on the left are considered 0). It remains to get the values from the integer and send them to the device. The expression val & 0x01 << i has value 0 if the bit at index i from the right in val is 0. Otherwise, the expression's value is a power of two
>>> for i in range(8):                                                                       
...     print(val & 0x01 << i)                                                               
... 
1
2
0
8
16
0
64
0
Calling GPIO.output(11, 1) and GPIO.output(12, 2) switches segments 11 and 12 on, in the same way GPIO.output(13, 0) switches segment 13 off, etc.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020