from machine import Pin
import utime
# Define GPIO pins for encoder
CLK_Pin = Pin(0, Pin.OUT) # CLK pin to send pulses
DT_Pin = Pin(1, Pin.OUT) # DT pin, used to simulate direction
value = 0
def rotate_encoder(direction, rotations):
# Constants for pulse timing
pulse_width = 1 # Pulse width in seconds (1 ms)
for _ in range(rotations):
if direction == 'clockwise':
CLK_Pin.value(1) # Send pulse
utime.sleep(pulse_width)
CLK_Pin.value(0) # End pulse
utime.sleep(pulse_width)
# Simulate direction (optional, depending on encoder type)
print("clock-wise")
DT_Pin.value(1)
elif direction == 'counter-clockwise':
CLK_Pin.value(1) # Send pulse
utime.sleep(pulse_width)
CLK_Pin.value(0) # End pulse
utime.sleep(pulse_width)
# Simulate direction (optional, depending on encoder type)
DT_Pin.value(0)
else:
print("Invalid direction")
return
print(f"Target rotations ({rotations}) achieved in direction: {direction}")
def rotary_changed(direction=None, rotations=0):
if direction and rotations > 0:
rotate_encoder(direction, rotations)
else:
print("No direction or invalid number of rotations provided")
# Example usage
direction = 'clockwise' # or 'counter-clockwise'
rotations = 10 # Number of pulses to simulate
# Simulate encoder rotation
rotary_changed(direction, rotations)
while True:
# Optionally, you can add code here to monitor the encoder state or handle button presses
utime.sleep(0.001)