#include <PID_v1.h>
// Pin Definitions
const int stepPin = 14;
const int dirPin = 12;
const int potPin = 34; // Potentiometer connected to ADC pin on ESP32 (e.g., GPIO34)
// PID variables
double setpoint = 7200; // Target steps per minute (36 RPM)
double input = 0; // Current step rate (from potentiometer feedback)
double output = 0; // PID output (to adjust step timing)
// PID tuning parameters
double Kp = 2.0; // Proportional gain
double Ki = 5.0; // Integral gain
double Kd = 1.0; // Derivative gain
// Create PID controller
PID myPID(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);
void setup() {
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
// Initialize the PID controller
myPID.SetMode(AUTOMATIC);
myPID.SetOutputLimits(500, 2000); // Limit PID output (delay in microseconds)
// Initialize serial communication
Serial.begin(115200);
}
void loop() {
// Read the potentiometer value
int potValue = analogRead(potPin); // ESP32 ADC returns values from 0 to 4095
input = map(potValue, 0, 4095, 0, 7200); // Map ADC value to steps per minute (0 to 7200)
// Compute PID output
myPID.Compute();
// Set motor direction (forward or reverse)
digitalWrite(dirPin, HIGH);
// Generate steps with delay from PID output
digitalWrite(stepPin, HIGH);
delayMicroseconds(output); // Delay controlled by PID output
digitalWrite(stepPin, LOW);
delayMicroseconds(output);
// Print values for graphing
Serial.print("Input: ");
Serial.print(input); // Current speed (steps per minute)
Serial.print(" Setpoint: ");
Serial.print(setpoint); // Desired speed (36 RPM = 7200 steps/minute)
Serial.print(" Output: ");
Serial.println(output); // PID output (delay for motor step timing)
}