# Dual 7 seg Range 0 to 99 & Dec point Pot controlled value Tony Goodhew 4 June 2019
# Only one LED is on at a time
# Hold button to slow down execution
import board
import gc
import time
from digitalio import DigitalInOut, Direction, Pull
from analogio import AnalogIn
gc.collect() # make some room

# Set up anodes
anodes = []
for p in [board.D13,board.D12,board.D11,board.D10,board.D9,board.D7,board.TX, board.RX]:
# Segment        A         B         C         D         E        F        G        dp
    anode = DigitalInOut(p)
    anode.direction = Direction.OUTPUT
    anodes.append(anode)

# Set up cathodes
cathodes = []
for p in [board.D3, board.D4]:
# cathodes:  units      tens
    cathode = DigitalInOut(p)
    cathode.direction = Direction.OUTPUT
    cathodes.append(cathode)

# Set up buttons
buttons = []
for p in [board.A0, board.A1]:  # Only A0 used here
    button = DigitalInOut(p)
    button.direction = Direction.INPUT
    button.pull = Pull.UP
    buttons.append(button)

# Set up pots
pots = []
for p in [board.A2, board.A3, board.A4]:  # Only A4 used here
    pot = AnalogIn(p)
    pots.append(pot)

#one row per digit - 0 to 9
nums =[1,1,1,1,1,1,0,  # 0
       0,1,1,0,0,0,0,  # 1
       1,1,0,1,1,0,1,  # 2
       1,1,1,1,0,0,1,  # 3
       0,1,1,0,0,1,1,  # 4
       1,0,1,1,0,1,1,  # 5
       1,0,1,1,1,1,1,  # 6
       1,1,1,0,0,0,0,  # 7
       1,1,1,1,1,1,1,  # 8
       1,1,1,0,0,1,1,  # 9
       0,0,0,0,0,0,1,  # -
       0,0,0,0,0,0,0]  # Blank

def show_num(val,col,dp): #Displays one digit briefly
    for x in range(2):
        cathodes[x].value = 1 # cathodes OFF
    cathodes[col].value = 0 # Turn col ON
    # set anodes
    offset = val * 7
    for p in range(offset,offset + 7):
        x=p-offset
        if nums[p] == 1:
            anodes[x].value = 1  # segment ON
            time.sleep(delay[speed]) #temp delay
            anodes[x].value = 0  # segment off
    # decimal point?
    if dp == col:
        anodes[7].value = 1  # Dp ON
        time.sleep(delay[speed]) #temp delay
        anodes[7].value = 0  # Dp off
    cathodes[col].value = 1  # Turn col off

def show_number(val):  #Base 10
    digits = [0,0]
    digits[0] = val % 10
    digits[1] = val // 10
    if val < 10:
        digits[1] = 11  # Suppress leading zero
    for cycle in range(loop[speed]): #show digit ? times
        for col in range(2):  # col equals 0 for units, and 1 for tens
            show_num(digits[col],col,0)  # Dp = col or -1

# +++ Main +++
print("\nPress left button to slow display\n")
print("Set Pot to zero and press button to HALT\n")
time.sleep(2)
delay = [0.1, 0.002]  # Second values are normal
loop = [1, 10]
print("Starting\n")
running = True
while running:
    speed = buttons[0].value  # Button pressed?
    pot = pots[2].value  # Read the potentiometer
    n = int(pot / 661.8) # Set range 0 to 99
    print(pot,n)
    show_number(n)       # Display number
    if speed == 0 and n == 0:  # Halt?
        running = False
print("\nFinished\n")