from machine import Pin, ADC
import time
# Define the GPIO pins for STEP, DIR, and the analog pin for the potentiometer
STEP_PIN = Pin(14, Pin.OUT) # GPIO pin for STEP
DIR_PIN = Pin(12, Pin.OUT) # GPIO pin for DIR
POT_PIN = ADC(Pin(26)) # Analog pin for potentiometer (e.g., GPIO 26 on ESP32)
# Define the number of steps per revolution for your motor
STEPS_PER_REV = 200
# Define the step delay (in seconds)
STEP_DELAY = 0.001
current_position = 0
def step_motor_forward():
STEP_PIN.value(1)
time.sleep(STEP_DELAY)
STEP_PIN.value(0)
time.sleep(STEP_DELAY)
def step_motor_back():
STEP_PIN.value(1)
time.sleep(STEP_DELAY)
STEP_PIN.value(0)
time.sleep(STEP_DELAY)
def map_value(value, in_min, in_max, out_min, out_max):
return int((value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
def rotate_to_angle_from_pot(pot_value):
angle = map_value(pot_value, 0, 65535, 0, 360) # Map 0-65535 (12-bit ADC) to 0-180 degrees
print("Rotating to:", angle, "degrees")
steps = int((angle / 360) * STEPS_PER_REV)
return steps
while True:
pot_value = POT_PIN.read_u16() # Read the potentiometer value
desired_position = rotate_to_angle_from_pot(pot_value)
# Move the motor to the desired position
if desired_position > current_position:
DIR_PIN.value(1) # Set direction forward
while current_position < desired_position:
step_motor_forward()
current_position += 1
elif desired_position < current_position:
DIR_PIN.value(0) # Set direction backward
while current_position > desired_position:
step_motor_back()
current_position -= 1
time.sleep(0.1) # Small delay to avoid excessive polling