import machine
import utime

# Wiring pins:
R1_CLK_PIN = 32
R1_DT_PIN = 33
R2_CLK_PIN = 25
R2_DT_PIN = 26
INCREMENT_OUT_LINE = 17
DECREMENT_OUT_LINE = 16
INCREMENT_BUT = 19
DECREMENT_BUT = 18

# Variables:
increment_timer = None
decrement_timer = None
increment_state = False
decrement_state = False

# Set pins as input/output
machine.Pin(R1_CLK_PIN, machine.Pin.IN)
machine.Pin(R1_DT_PIN, machine.Pin.IN)
machine.Pin(INCREMENT_OUT_LINE, machine.Pin.OUT)
machine.Pin(DECREMENT_OUT_LINE, machine.Pin.OUT)
machine.Pin(INCREMENT_OUT_LINE).value(1)
machine.Pin(DECREMENT_OUT_LINE).value(1)
machine.Pin(INCREMENT_BUT, machine.Pin.IN, machine.Pin.PULL_UP)
machine.Pin(DECREMENT_BUT, machine.Pin.IN, machine.Pin.PULL_UP)

# Test message (code working)
print("Running code...")

# Read initial state of CLK pin
r1_last_clk_state = machine.Pin(R1_CLK_PIN).value()

# Loop function
while True:
    r1_current_clk_state = machine.Pin(R1_CLK_PIN).value()

    if r1_current_clk_state != r1_last_clk_state and r1_current_clk_state == 1:

        # If the rotary encoder position changed
        if machine.Pin(R1_DT_PIN).value() != r1_current_clk_state: #CCW = decrement
            if (increment_state == True):
              increment_timer += 100
            else:
              increment_state = True
              increment_timer = utime.ticks_ms() + 100

            machine.Pin(INCREMENT_OUT_LINE).value(0)

        else: #CW = increment
            if (decrement_state == True):
              decrement_timer += 100
            else:
              decrement_state = True
              decrement_timer = utime.ticks_ms() + 100
            
            machine.Pin(DECREMENT_OUT_LINE).value(0)
            
    r1_last_clk_state = r1_current_clk_state

    # Increment timer
    if(increment_state == True and increment_timer < utime.ticks_ms()):
      increment_state = False
      machine.Pin(INCREMENT_OUT_LINE).value(1)

    # Decrement timer
    if(decrement_state == True and decrement_timer < utime.ticks_ms()):
      decrement_state = False
      machine.Pin(DECREMENT_OUT_LINE).value(1)

    # Increment switch
    if(machine.Pin(INCREMENT_BUT).value() == False):
      machine.Pin(INCREMENT_OUT_LINE).value(0)
      while(machine.Pin(INCREMENT_BUT).value() == False):
        pass
      machine.Pin(INCREMENT_OUT_LINE).value(1)
      
    # Decrement switch
    if(machine.Pin(DECREMENT_BUT).value() == False):
      machine.Pin(DECREMENT_OUT_LINE).value(0)
      while(machine.Pin(DECREMENT_BUT).value() == False):
        pass
      machine.Pin(DECREMENT_OUT_LINE).value(1)

    # Put in a slight delay to help debounce the reading
    utime.sleep_ms(1)
Increment
Decrement
Increment status LED
Decrement status LED