#https://community.element14.com/challenges-projects/project14/7segmentdisplay/b/blog/posts/electronic-die
#
# -scottiebabe 2022
from machine import Pin, mem32
import time
import random

# Configure GP26 as input with internal pull-up
pb = Pin(26,Pin.IN,Pin.PULL_UP)

# Configure GP14 - GP21 as outputs
PinBus = [ Pin(x,Pin.OUT) for x in range(14,22) ]

def _BusWrite2( pbus, v ):
    for i in range(len(pbus)):
        pbus[i].value( v & (1<<i))

SIO_BASE = 0xd0000000 
def BusWrite( b0, bn, v ):
    n = bn-b0+1
    bitmask = (0xFFFFFFFF >> (32-n)) << b0
    scratch = mem32[SIO_BASE+0x10] # read GPIO output reg
    scratch &= ~bitmask
    scratch |= v << b0
    mem32[SIO_BASE+0x10] =  scratch

# Seven segment LUT table for numerical readout
# bit0 - segA, bit1 - segB,... bit7 - segDP
SGLUT = [ ~x for x in [0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71]]

def displaySevenSeg(v):
    BusWrite(14,21,SGLUT[v])
    #BusWrite(PinBus,SGLUT[v])

#BusWrite(PinBus,0xff)
BusWrite(14,21,0xff)
while True:
    if pb.value() == 0:
        # display a die rolling
        for i in range(30):
            #BusWrite(PinBus,~(1 << (i%6)))
            BusWrite(14,21,~(1 << (i%6)))
            time.sleep(0.1)
        displaySevenSeg(random.randint(1,6))

print("Hello, Internet Friends :) !")
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT