Tinkercad Pid — Control //free\\
// Pin Definitions const int setpointPin = A0; const int feedbackPin = A1; const int pwmPin = 9; const int dirPin1 = 8; const int dirPin2 = 7; // PID Tuning Constants double Kp = 2.0; // Proportional Gain double Ki = 0.5; // Integral Gain double Kd = 0.1; // Derivative Gain // Variables for PID calculation double error = 0; double lastError = 0; double integral = 0; double derivative = 0; double output = 0; // Timing variables unsigned long lastTime = 0; void setup() pinMode(pwmPin, OUTPUT); pinMode(dirPin1, OUTPUT); pinMode(dirPin2, OUTPUT); Serial.begin(9600); void loop() // Calculate elapsed time unsigned long currentTime = millis(); double deltaTime = (double)(currentTime - lastTime) / 1000.0; if (deltaTime >= 0.05) // Run the loop every 50ms // Read sensor inputs (0 to 1023) double setpoint = analogRead(setpointPin); double feedback = analogRead(feedbackPin); // Calculate error error = setpoint - feedback; // Calculate Integral with anti-windup protection integral += error * deltaTime; integral = constrain(integral, -100, 100); // Calculate Derivative derivative = (error - lastError) / deltaTime; // Compute total PID output output = (Kp * error) + (Ki * integral) + (Kd * derivative); // Drive the system based on output controlMotor(output); // Debugging data for Tinkercad Serial Plotter Serial.print("Setpoint:"); Serial.print(setpoint); Serial.print(","); Serial.print("Feedback:"); Serial.print(feedback); Serial.print(","); Serial.print("Output:"); Serial.println(output); // Save state for next iteration lastError = error; lastTime = currentTime; void controlMotor(double pidOutput) // Constrain output to valid PWM range (-255 to 255) int speed = constrain(abs(pidOutput), 0, 255); if (pidOutput > 0) digitalWrite(dirPin1, HIGH); digitalWrite(dirPin2, LOW); else digitalWrite(dirPin1, LOW); digitalWrite(dirPin2, HIGH); analogWrite(pwmPin, speed); Use code with caution. Simulating and Tuning Your PID Loop
In an ideal world, you would calculate these gains mathematically. In reality, you simulate, tune, and iterate. tinkercad pid control
Open Tinkercad and start a new Circuits project. Drag these components onto the breadboard: // Pin Definitions const int setpointPin = A0;
Corrects based on the Current Error (Target - Actual). If the error is large, the motor gets a large boost. Open Tinkercad and start a new Circuits project