// Define pins
const int potPin = 2; // Potentiometer connected to analog pin (GPIO 34)
const int stepPin = 16; // Stepper motor step pin connected to GPIO 16
const int dirPin = 4; // Stepper motor direction pin connected to GPIO 4
const int enablePin = 0; // Stepper motor enable pin connected to GPIO 0 (optional)
// Variables
int potValue = 0; // Variable to store potentiometer value
int lastPotValue = 0; // Variable to store the last potentiometer value
int stepsPerRevolution = 200; // Full steps per revolution for the stepper motor
int totalSteps = stepsPerRevolution * 10; // Total steps for 10 full revolutions
int stepDelay = 1500; // Delay between steps in microseconds
void setup() {
// Initialize serial communication for debugging
Serial.begin(115200);
// Set stepper motor pins as output
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enablePin, OUTPUT);
// Enable the motor
digitalWrite(enablePin, LOW); // Enable motor driver (set LOW to enable)
}
void loop() {
// Read the potentiometer value (0 to 4095 for ESP32)
potValue = analogRead(potPin);
// Map the potentiometer value to a larger range of steps (0 to totalSteps)
int targetPosition = map(potValue, 0, 4095, 0, totalSteps);
// Determine direction based on potentiometer movement
if (targetPosition > lastPotValue) {
digitalWrite(dirPin, HIGH); // Set direction to forward (clockwise)
} else if (targetPosition < lastPotValue) {
digitalWrite(dirPin, LOW); // Set direction to reverse (counterclockwise)
}
// Calculate the number of steps to move
int stepsToMove = abs(targetPosition - lastPotValue);
// Move the stepper motor by the required number of steps
for (int i = 0; i < stepsToMove; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(stepDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay);
}
// Update last potentiometer value
lastPotValue = targetPosition;
// Optional: Add a small delay to avoid jitter
delay(10);
}