from machine import Pin
import time
# Define pins for encoder input
pinA = Pin(12, Pin.IN)
pinB = Pin(13, Pin.IN)
# Initialize variables for encoder state and position
encoder_state = 0
encoder_position = 0
def encoder_callback(pin):
global encoder_state, encoder_position
# Determine which pin triggered the interrupt
pinA_state = pinA.value()
pinB_state = pinB.value()
# Update encoder state based on transition
if pin == pinA and pinA_state != pinB_state:
encoder_state = (encoder_state << 2) | 1
elif pin == pinB and pinA_state == pinB_state:
encoder_state = (encoder_state << 2) | 2
else:
encoder_state = 0
# Update encoder position based on encoder state
if encoder_state in [0b0010, 0b0111, 0b1101, 0b1000]:
encoder_position += 1
elif encoder_state in [0b0001, 0b1110, 0b1010, 0b0101]:
encoder_position -= 1
if encoder_position == 1:
print("正转")
elif encoder_position == -1:
print("反转")
# Attach interrupt handlers to encoder pins
pinA.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=encoder_callback)
pinB.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=encoder_callback)
while True:
pass