Skip to content

Instantly share code, notes, and snippets.

@chaosmail
Last active September 26, 2022 13:13
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save chaosmail/8372717 to your computer and use it in GitHub Desktop.
Save chaosmail/8372717 to your computer and use it in GitHub Desktop.
Simple PID Controller
def pid_controller(y, yc, h=1, Ti=1, Td=1, Kp=1, u0=0, e0=0)
"""Calculate System Input using a PID Controller
Arguments:
y .. Measured Output of the System
yc .. Desired Output of the System
h .. Sampling Time
Kp .. Controller Gain Constant
Ti .. Controller Integration Constant
Td .. Controller Derivation Constant
u0 .. Initial state of the integrator
e0 .. Initial error
Make sure this function gets called every h seconds!
"""
# Step variable
k = 0
# Initialization
ui_prev = u0
e_prev = e0
while 1:
# Error between the desired and actual output
e = yc - y
# Integration Input
ui = ui_prev + 1/Ti * h*e
# Derivation Input
ud = 1/Td * (e - e_prev)/h
# Adjust previous values
e_prev = e
ui_prev = ui
# Calculate input for the system
u = Kp * (e + ui + ud)
k += 1
yield u
@rpbeltran
Copy link

rpbeltran commented Nov 4, 2016

Lines 30 and 32, shouldn't it be:
ui = ui_prev + 1.0 / Ti * h * e
and
ud = 1.0 / Td * (e - e_prev) / float( h)

I changed the 1s to 1.0,and cast h to a float, otherwise I think this would produce incorrect results when your control constants, or sampling time are not 1.

@rtennill
Copy link

rtennill commented Mar 8, 2018

If you're running python2 you'll need to make them floats as you have shown or add this import:
from __future__ import division

I don't think there are any changes required for Python 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment