from machine import Pin
from time import sleep
import tm1637
tm = tm1637.TM1637(clk=Pin(4), dio=Pin(5))
RoA_Pin = 0 # CLK
RoB_Pin = 1 # DT
Btn_Pin = 2 # SW
globalCounter = 0 # valor del contador
flag = 0 # Marca de si ocurrió una rotación
Last_RoB_Status = 0 # Estado de DT
Current_RoB_Status = 0 # Estado de CLK
def setup():
global clk_RoA
global dt_RoB
global sw_BtN
clk_RoA = Pin(RoA_Pin, Pin.IN)
dt_RoB = Pin(RoB_Pin, Pin.IN)
sw_BtN = Pin(Btn_Pin, Pin.IN, Pin.PULL_UP)
# Inicializar la función de interrupción, cuando el pin SW es 0, se habilita la interrupción
sw_BtN.irq(trigger=Pin.IRQ_FALLING, handler=btnISR)
# Función para tratar la rotación y determinar la dirección
def rotaryDeal():
global flag
global Last_RoB_Status
global Current_RoB_Status
global globalCounter
Last_RoB_Status = dt_RoB.value()
# Verificar el cambio de nivel del pin CLK para determinar la dirección
while not clk_RoA.value():
Current_RoB_Status = dt_RoB.value()
flag = 1 # Marca de que ocurrió una rotación
if flag == 1: # Si la marca de rotación es 1, ocurrió una rotación
flag = 0 # Resetear la marca
if (Last_RoB_Status == 0) and (Current_RoB_Status == 1):
globalCounter += 1 # Rotación en sentido contrario a las agujas del reloj, positivo
if (Last_RoB_Status == 1) and (Current_RoB_Status == 0):
globalCounter -= 1 # Rotación en el sentido de las agujas del reloj, negativo
# Función de interrupción, cuando el pin SW está en 0, se habilita la interrupción
def btnISR(chn):
global globalCounter
globalCounter = 0
print('globalCounter = %d' % globalCounter)
while True:
# Contador que cambia cada 1 segundo
tm.number(globalCounter)
globalCounter -= 1
sleep(1)
if globalCounter == 0:
break
def loop():
global globalCounter
tmp = 0
while True:
rotaryDeal()
if tmp != globalCounter:
print('globalCounter = %d' % globalCounter)
tmp = globalCounter
tm.number(globalCounter)
if __name__ == '__main__':
setup()
loop()