binary counting with a 7 segment LCD



  • here is some code to draw a 7 segment LCD and use the segments to count up to 127 (2**7-1).

    
    class digit(object):
    	"""a digit of the lcd display"""
    	def __init__(self, pos, size, seg_l, seg_h):
    		self.pos    = pos
    		self.size   = size
    		self.seg_l  = seg_l
    		self.seg_h  = seg_h
    
    	def draw_segment(self, indx, l, h):
    		seg_poss = [
    			(           0,  self.size),
    			( self.size/2,  self.size/2),
    			( self.size/2, -self.size/2),
    			(           0, -self.size),
    			(-self.size/2, -self.size/2),
    			(-self.size/2,  self.size/2),
    			(           0,  0), ]
    
    		x = self.pos[0] + seg_poss[indx][0]
    		y = self.pos[1] + seg_poss[indx][1]  
    
    		if indx in [1, 2, 4, 5]:
    			polygon(
    				(x, y + l/2),
    				(x - h/2, y + l/2 - h/2),
    				(x - h/2, y - l/2 + h/2),
    				(x, y - l/2),
    				(x + h/2, y - l/2 + h/2),
    				(x + h/2, y + l/2 - h/2),)
    		else: 		
    			polygon(
    				(x + l/2, y),
    				(x + l/2 - h/2, y + h/2),
    				(x - l/2 + h/2, y + h/2),
    				(x - l/2, y),
    				(x - l/2 + h/2, y - h/2),
    				(x + l/2 - h/2, y - h/2),)
    
    	def draw(self, num):
    		for s in range(7):
    			if (num & (1<<s)):
    				self.draw_segment(s, self.seg_l, self.seg_h)
    
    # ---------------------------
     
    int_to_bin = {
        0 :  63,
        1 :   6,
        2 :  91,
        3 :  79,
        4 : 102, 
        5 : 109, 
        6 : 125,
        7 :   7,
        8 : 127,
        9 : 111,
        }
    
    # ---------------------------
    
    PW, PH = 500, 500
    
    d  = digit((0, 0), PW/3, 150, 30)
    d_int = digit((PW*.5, -PH*.4), 16, 14, 4)
    
    
    for n in range(128):
        assert (0 <= n < 128), "Values should be higher than -1 and smaller than 128!"    
        newPage(PW, PH)
        fill(.2)
        rect(0, 0, PW, PH)
        translate(PW/2, PH/2)
        skew(2)
        fill(0, 1, 0)
        d.seg_h = n+4
        d.draw(n)
    
        with savedState():
            for i in reversed(str(n)):
                translate(-30)
                d_int.draw(int_to_bin[int(i)])         
    

    should make animations like this:

    bin_count2.gif


Log in to reply