In an ideal world, you would calculate these gains mathematically. In reality, you simulate, tune, and iterate.
// PID Control Testbed for Tinkercad #include Servo myServo; // Pins const int pwmPin = 3; // Actuator output (Control Variable) const int analogPin = A0; // Sensor input (Process Variable) const int servoPin = 9; // Visual output // PID Parameters (Tune these values!) double Kp = 2.5; double Ki = 0.5; double Kd = 0.1; // Control Variables double setpoint = 512; // Target value (Mid-point of 0-1023 analog range) double input = 0; double output = 0; // Variables for tracking error and time double lastInput = 0; double errorSum = 0; unsigned long lastTime = 0; double sampleTime = 100; // Sample time in milliseconds (0.1 seconds) void setup() Serial.begin(9600); pinMode(pwmPin, OUTPUT); myServo.attach(servoPin); lastTime = millis(); void loop() unsigned long now = millis(); unsigned long timeChange = now - lastTime; // Execute PID calculation at strict sample intervals if (timeChange >= sampleTime) // Read the current state (Process Variable) input = analogRead(analogPin); // Calculate error metrics double error = setpoint - input; errorSum += error * (sampleTime / 1000.0); // Integrate over time (seconds) // Constrain Integral windup to prevent runaway accumulation errorSum = constrain(errorSum, -255, 255); double dInput = (input - lastInput) / (sampleTime / 1000.0); // Derivative term // Compute the PID Output output = (Kp * error) + (Ki * errorSum) - (Kd * dInput); // Constrain output to valid PWM boundaries (0 - 255) output = constrain(output, 0, 255); // Apply output to the system analogWrite(pwmPin, output); // Map output to Servo for visual movement int servoAngle = map(input, 0, 1023, 0, 180); myServo.write(servoAngle); // Debugging output to Serial Plotter Serial.print("Setpoint:"); Serial.print(setpoint); Serial.print(","); Serial.print("Input_PV:"); Serial.print(input); Serial.print(","); Serial.print("Output_PWM:"); Serial.println(output); // Save state variables for the next cycle lastInput = input; lastTime = now; Use code with caution. 4. Tuning Your PID Controller tinkercad pid control
Write an algorithm that automatically measures the oscillation period and calculates optimal Kp, Ki, Kd using the Ziegler-Nichols method. This is an advanced challenge that Tinkercad is perfect for, as you can run 100 simulations instantly. In an ideal world, you would calculate these
As you change the temperature slider, you will observe the lines adjusting dynamically: As you change the temperature slider, you will
A DC motor speed control system is the classic PID exercise. The goal is to make the motor reach and maintain a desired RPM (setpoint) despite load variations, using an encoder for feedback.