Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Created February 28, 2017 12:47
Show Gist options
  • Save pythonhacker/65639f7738b9ef1da9f465e3ead7e467 to your computer and use it in GitHub Desktop.
Save pythonhacker/65639f7738b9ef1da9f465e3ead7e467 to your computer and use it in GitHub Desktop.
Light an LED digit on the console using Python
"""
A Python program to light an LED digit on console
Author: anandpillai@letterboxes.org
"""
import sys
class LEDMatrix(object):
""" A simple led matrix class """
# LED action config for numbers from 0..9
config = { 1: [(1, 3)],
2: [(0,1), (1, 3, 1), (0,4), (1,1,2), (0,7)],
3: [(0,1), (1, 3, 1), (0,4), (1,3,2), (0,7)],
4: [(1, 1, 1), (0,4), (1,3)],
5: [(0,1), (1, 1, 1), (0,4), (1,3,2), (0,7)],
6: [(0,1), (1, 1, 1), (0,4), (1,1,2), (1,3,2), (0,7)],
7: [(0,1), (1, 3)],
8: [(0,1), (1, 1), (0,4), (1,3), (0,7)],
9: [(0,1), (1, 1, 1), (0,4), (1,3), (0,7)],
0: [(0,1), (1, 1), (1,3), (0,7)] }
def __init__(self, m, n, init=True, sep='\t', led='*'):
if init:
self.rows = [[0]*n for x in range(m)]
else:
self.rows = []
self.m = m
self.n = n
# Separator gap
self.sep = sep
# LED character
self.led = led
# Action map
self.action_map = {0: 'row_on',
1: 'col_on'}
def __str__(self):
s='\n'.join([self.sep + ' '.join([str(item) for item in row]) for row in self.rows])
return s + '\n'
def col_on(self, cno, mode=0):
""" Turn on a specific column """
# 0=> full
# 1 => top half
# 2 => bottom half
rng = { 0: range(self.m),
1: range(self.m/2),
2: range(self.m/2, self.m) }
for i in rng.get(mode):
# print row
row = self.rows[i]
row[cno-1] = self.led
def row_on(self, rno):
""" Turn on a specific row """
row = self.rows[rno-1]
for i in range(self.n):
row[i] = self.led
def blank(self):
""" Blank the matrix """
self.rows = [[' ']*self.n for x in range(self.m)]
def display(self, num):
""" Display a number on the LED Matrix """
self.blank()
actions = self.config.get(num)
for action in actions:
func = getattr(self, self.action_map.get(action[0]))
args = action[1:]
# print args
func(*args)
print self
class LEDPanel(object):
""" An LED panel class using the LED matrices """
def __init__(self, size=3):
self.matrices = []
for i in range(size):
self.matrices.append(LEDMatrix(7, 3, sep='\t', led='0'))
def display(self, number):
""" Display a number """
# Stringify it
num_s = str(number)
for idx,num in enumerate(num_s):
self.matrices[idx].display(int(num))
if __name__ == "__main__":
# m = LEDMatrix(7, 3)
# Usage: python led_digit.py <digit>
# Example: python led_digit.py 1
p = LEDPanel()
p.display(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment