'''
AIM:Design the schematic circuit using stepper motor and rotary
encoder with raspberry pico microcontroller in Wokwi platform.
Write code to control the steps and direction of stepper motor
through rotary motor.
'''
from machine import Pin
import time
# Setup pins
clk = Pin(14, Pin.IN, Pin.PULL_UP)
dt = Pin(15, Pin.IN, Pin.PULL_UP)
btn = Pin(16, Pin.IN, Pin.PULL_UP)
dir_pin = Pin(2, Pin.OUT)
step_pin = Pin(3, Pin.OUT)
# Variables
position = 0
last_clk = clk.value()
print("Simple Stepper Control")
print("Rotate encoder to move")
while True:
# Read encoder
clk_state = clk.value()
dt_state = dt.value()
# Check if encoder rotated
if clk_state != last_clk:
if dt_state != clk_state:
# Clockwise
if position < 200:
position += 1
dir_pin.value(1)
else:
# Counter-clockwise
if position > -200:
position -= 1
dir_pin.value(0)
# Move stepper one step
step_pin.on() #clockwise direction
time.sleep(0.001)
step_pin.off() # anticlockwise direction
time.sleep(0.001)
print(f"Position: {position}")
last_clk = clk_state
# Check button
if btn.value() == 0:
position = 0
print("Reset to 0")
time.sleep(0.5) # Debounce
time.sleep(0.001)