Advertisement
Musical_Muze

Binary Counter Using a Shift Register

Aug 7th, 2022
1,964
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. import RPi.GPIO as IO
  2. import time
  3.  
  4. IO.setwarnings(False)
  5. IO.setmode(IO.BCM)
  6. IO.setup(18,IO.OUT)     #data pin on the shift register
  7. IO.setup(23,IO.OUT)     #push pin on the shift register
  8. IO.setup(24,IO.OUT)     #display pin on the shift register
  9.  
  10. #function to convert decimal number to an array of integers representing the binary equivalent of the decimal
  11. def convert_to_binary(decimal):
  12.  
  13.     #convert decimal number to binary number
  14.     passthrough = format(decimal, 'b')
  15.  
  16.     #convert the binary number into an array of strings
  17.     binary = list(passthrough)
  18.  
  19.     #pad the array to be 8 digits if necessary. now array is a mix of integers and strings
  20.     while len(binary)< 8:
  21.         binary.insert(0,0)
  22.  
  23.     #convert all array items to integers
  24.     for i in range(8):
  25.         binary[i] = int(binary[i])
  26.  
  27.     #output the array of integers
  28.     return binary
  29.  
  30. #function to output binary array to the LEDs
  31. def led_output(bin_arr):
  32.     flip = bin_arr[::-1]            #because of how a shift register works, we need to reverse the array then
  33.                                    #send it to the register
  34.  
  35.     for x in flip:     #iterate through the array and turn on/off an LED depending on the value of the item
  36.         if x == 1:
  37.             IO.output(18,1)
  38.         IO.output(23,1)
  39.         IO.output(23,0)
  40.         IO.output(18,0)
  41.        
  42.     IO.output(24,1)
  43.     IO.output(24,0)
  44.  
  45. #function to clear the LEDs
  46. def led_clear():
  47.     for z in range (8):
  48.         IO.output(18,0)
  49.         IO.output(23,1)
  50.         IO.output(23,0)
  51.        
  52.     IO.output(24,1)
  53.     IO.output(24,0)
  54.    
  55. #count from 0 to 255 and output the binary number to the LEDs
  56. for num in range(256):
  57.     led_output(convert_to_binary(num))
  58.     time.sleep(0.2)
  59.     led_clear()
  60.  
  61. #count from 254 to 0 and output the binary number to the LEDs
  62. for num in range(254,-1,-1):
  63.     led_output(convert_to_binary(num))
  64.     time.sleep(0.2)
  65.     led_clear()
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement