Skip to content

Instantly share code, notes, and snippets.

@wheremyfoodat
Created June 22, 2025 16:50
Show Gist options
  • Save wheremyfoodat/004d171382df2171cc681a24c07e890c to your computer and use it in GitHub Desktop.
Save wheremyfoodat/004d171382df2171cc681a24c07e890c to your computer and use it in GitHub Desktop.
Calculate coefficients for a PID controller, using the various formulae for the Ziegler-Nichols method
import sys
if len(sys.argv) < 3:
print("Error: Missing arguments. Pls provide the ultimate gain (Ku) and ultimate period (Tu) of your plant.")
print("Usage: python3 pid.py <Ku> <Tu>")
sys.exit(-1)
# PID coefficients (Kp/Kd/Ki and Tp/Ti)
class Coefficients:
def __init__(self, Kp, Ki, Kd):
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
# Methods for calculating Kp/Ki/Kd from Ku and Tu
# https://en.wikipedia.org/wiki/Ziegler%E2%80%93Nichols_method
def classicPID(Ku, Tu):
return Coefficients(Kp = 0.7 * Ku, Ki = 1.75 * Ku / Tu, Kd = 0.105 * Ku * Tu)
def someOvershoot(Ku, Tu):
return Coefficients(Kp = 0.333333 * Ku, Ki = 0.6666666 * Ku / Tu, Kd = 0.111111 * Ku * Tu)
def noOvershoot(Ku, Tu):
return Coefficients(Kp = 0.2 * Ku, Ki = 0.4 * Ku / Tu, Kd = 0.0666666 * Ku * Tu)
def printCoefficients(name, coeffs):
print("{} Coefficients:".format(name))
print("Kp: {:.4f}".format(coeffs.Kp))
print("Ki: {:.4f}".format(coeffs.Ki))
print("Kd: {:.4f}".format(coeffs.Kd))
print("-" * 30)
Ku = float(sys.argv[1])
Tu = float(sys.argv[2])
print("Tuning PID controller with Ku = {} and Tu = {} seconds".format(Ku,Tu))
print("")
printCoefficients("Classic PID", classicPID(Ku, Tu))
printCoefficients("Some Overshoot", someOvershoot(Ku, Tu))
printCoefficients("No Overshoot", noOvershoot(Ku, Tu))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment