Introduction
Ever wondered if there’s a less conventional yet effective way to tune a PID controller? Well, Python can help! As far as you know (even approximately) your plant model, Python has got you covered. This blog post will deep dive into how you can achieve optimal PID tuning by leveraging Python code. Let’s get started!
What is PID Tuning?
PID tuning involves adjusting the parameters of a PID controller to optimize system performance. The PID controller equation with filtered derivative and back-calculation anti-windup is as follows:
![]()
Here, is the saturated command and![]()
.![]()
Finding the Optimal PID Parameters
The objective of tuning is to find the best combination of PID parameters that gives us satisfactory control performance results.![]()
When we know the physics of the system that we want to control we can build a model and turn the tuning problem in an optimisation problem aimed to minimize a specific cost function, for example:
![Rendered by QuickLaTeX.com \[J = \sum_{i=1}^{N-1} \left[ W_e \times (r_i - y_i)^2 + W_u \times u_{sat_i}^2 \right]\]](https://simonebertonilab.com/wp-content/ql-cache/quicklatex.com-44ae636802d9e2eae8800af187afd96b_l3.png)
where:
: setpoint
: controlled variable
: saturated command
: weighting coefficient related to the control error
: weighting coefficient related to 
The Weighting Coefficients
and ![]()
are the weighting coefficient and their choice determines the compromise between minimizing the error and minimizing the control effort:![]()
: Minimizing the error takes precedence over minimizing control effort.
: Minimizing control effort is more important than minimizing the error.
PID Tuning in Python – A Practical Example
The Plant Model
For our example, let’s consider an object with a mass kg, which slides on a surface experiencing a viscous friction of coefficient ![]()
Ns/m, and is pushed by a force
(our control input). The dynamic equation is:![]()
![]()

The Python Code
The code developed for this example includes:
- A “PID” class for PID control with filtered derivative and back-calculation anti-windup.
- An “Object” class representing the plant.
- A “Simulation” function that runs an 80-second simulation.
- A “Cost” function that calculates
using the various PID parameters.
You can find the complete Python code at this GitHub link.

Results
Here are three different configurations with their performance results:
Identical Weights
, 
- Result:
,
,
,
, 
Focus on Error Minimization
, 
- Result:
,
,
,
, 
Focus on Control Effort Minimization
, 
- Result:
,
,
,
, 

Conclusion
Python offers a versatile and free platform that can be used for PID tuning (amongst many other things), allowing for precise optimization based on your specific needs.
By understanding the role of the cost function
and its weighting coefficients ( and ![]()
in this example), you can find the perfect combination of parameters that suits your needs.![]()
Happy PID tuning!




