2 - Cycling Through All Segments

Video

Writing the Code

Start by importing modules and objects we'll be using.
​
Create a DigitalInOut object for each of the I/O pins we need to control. By default they all start off as inputs but we need to make them outputs if we're going to send signals with them. We could do this line-by-line by using each object's switch_to_output() method, but there's faster to get this done and set us up for easier control later on.
​
We're going to create two lists, one for segments and one for digits. This will make it easy to iterate over the objects in the list using for-loops!
​
These for-loops let us run the .switch_to_output() method for each of the objects in the list. Now all our segments and digits are ready to be used as outputs.
​
Now that our setup is done, we'll write a while-loop that runs forever.
​
We know we can only have one digit active at a time, so we'll make a for-loop that iterates over the list of digits, activates the current digit, then deactivates it, and so on and so forth for each digit, forever.
​
Next we'll create a for-loop that iterates through our entire list of segments, each time we activate a new digit. Placing a loop within a loop is known as 'nesting'. Here we've created nested-for-loops. This inner loop is where we need to put our delay, otherwise it would cycle through every segment so quickly it would appear as though they're all on at the same time. We have 9 segments and 4 digits, each being shown for 0.1 seconds, so it should take 3.6 seconds to complete the entire cycle.
​

Code

import board
from digitalio import DigitalInOut
import time
​
# Create DigitalInOut objects for each segment
A = DigitalInOut(board.GP10)
B = DigitalInOut(board.GP14)
C = DigitalInOut(board.GP5)
D = DigitalInOut(board.GP2)
E = DigitalInOut(board.GP4)
F = DigitalInOut(board.GP11)
G = DigitalInOut(board.GP13)
DP = DigitalInOut(board.GP3) # Decimal Point
COL = DigitalInOut(board.GP12) # Colon
​
# Create DigitalInOut objects for each digit
D1 = DigitalInOut(board.GP6)
D2 = DigitalInOut(board.GP7)
D3 = DigitalInOut(board.GP8)
D4 = DigitalInOut(board.GP9)
​
# Create a list containing all the segments
segments = [A,B,C,D,E,F,G,DP,COL]
​
# Create a list containing all the digits
digits = [D1,D2,D3,D4]
​
# Set all the segments as outputs
for seg in segments:
seg.switch_to_output()
# Set all digits as outputs
for dig in digits:
dig.switch_to_output()
​
while True: # Loop Forever:
for dig in digits: # Iterate through all digits:
dig.value = True # Activate the current digit
for seg in segments: # Iterate through all segments:
seg.value = True # Activate the current segment
time.sleep(0.1) # Do nothing for 0.1 seconds
seg.value = False # Deactivate the current segment
dig.value = False # Deactivate the current digit
​