from machine import Pin
import time

# Configura los pines GPIO de PICO CON 74HC595
ds_pin = machine.Pin(13, machine.Pin.OUT)#DS
stcp_pin = machine.Pin(14, machine.Pin.OUT)#STCP
shcp_pin = machine.Pin(15, machine.Pin.OUT)#SHCP

# Configura los pines GPIO de PICO CON 74LS165
latch_pin = Pin(17, Pin.OUT)#PL
clock_pin = Pin(18, Pin.OUT)#CP
data_pin = Pin(16, Pin.IN)#Q7

old_option_switch = 0
clock_pin.value(0)
latch_pin.value(1)

def decimal_a_binario(decimal):
  if decimal <= 0:
      return "0"
  # Aquí almacenamos el resultado
  binario = ""
  # Mientras se pueda dividir...
  while decimal > 0:
      # Saber si es 1 o 0
      residuo = int(decimal % 2)
      # E ir dividiendo el decimal
      decimal = int(decimal / 2)
      # Ir agregando el número (1 o 0) a la izquierda del resultado
      binario = str(residuo) + binario
  return binario

def ReadOne165():
  ret = 0x00
  # The first one that is read is the highest bit (input D7 of the 74HC165).
  for i in range(7, -1, -1):
    if data_pin.value() == 1:
      ret |= 1 << i

    clock_pin.value(1)
    time.sleep_us(10)
    clock_pin.value(0)
  return ret

# Función para leer datos del chip 74LS165(cascada infinita)
def read_shift_register(total_74ls165):
  global old_option_switch
  latch_pin.value(0)
  time.sleep_us(10)
  latch_pin.value(1)

  option_switch = 0
  for i in range((total_74ls165-1)*8, -1, -8):
    option_switch |= ReadOne165() << i
  entrada_bin = decimal_a_binario(option_switch)
  salida_bin = '0b' + entrada_bin
  old_option_switch = option_switch
  print(salida_bin)
  return salida_bin

# Función para enviar datos al chip 74HC595(cascada infinita)
def shift_out(bit_order, val, cascade):
  for i in range(8*cascade):
      if bit_order == 'msb':
          bit = val & (1 << ((8*cascade)-1 - i))
      else:
          bit = val & (1 << i)
      ds_pin.value(bit)
      shcp_pin.value(1)
      shcp_pin.value(0)
  stcp_pin.value(1)
  stcp_pin.value(0)

while True:
    shift_out('msb',int(read_shift_register(3)),3)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
74HC165
74HC165
74HC165
74HC595
74HC595
74HC595