import machine
import utime as time
from machine import Pin
# LED Pin initialization
led1 = Pin(19, Pin.IN)
led2 = Pin(18, Pin.IN)
led3 = Pin(5, Pin.IN)
led4 = Pin(17, Pin.IN)
# Rotary encoder input pins
clk = Pin(26, Pin.IN, Pin.PULL_DOWN) # Using CLK (A) pin 26
dt = Pin(27, Pin.IN, Pin.PULL_DOWN) # Using DT (B) pin 27
# Initialize the rotary encoder angle
angle = 0
step = 360 / 20
def rotary_change(pin):
global angle
# Read current state of CLK
current_state_clk = clk.value()
# If last and current state of CLK are different, then we have a pulse
# We only react to HIGH to LOW change
if (dt.value() != current_state_clk): # If DT state is different than CLK, rotate clockwise
angle += step
print("Clockwise")
else:
angle -= step
print("CounterClockwise")
# Ensure the angle is always between 0 and 360 degrees
angle = (angle + 360) % 360
print("Angle:", angle)
# LED control based on angle range
if angle < 80:
led1.off()
led2.off()
led3.off()
led4.off()
elif angle < 160:
led1.on()
led2.off()
led3.off()
led4.off()
elif angle < 240:
led1.on()
led2.on()
led3.off()
led4.off()
elif angle < 320:
led1.on()
led2.on()
led3.on()
led4.off()
else:
led1.on()
led2.on()
led3.on()
led4.on()
# Add a small delay to avoid immediate interrupts at startup
time.sleep(0.5) # Give some time for the pins to stabilize
# Set up interrupt for rotary encoder change
clk.irq(handler=rotary_change, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING)
# Main loop to keep the program running
while True:
time.sleep(0.1)