Skip to content

Instantly share code, notes, and snippets.

@lazyval
Last active August 29, 2015 14:20
Show Gist options
  • Save lazyval/de508dc5ca90c966152e to your computer and use it in GitHub Desktop.
Save lazyval/de508dc5ca90c966152e to your computer and use it in GitHub Desktop.
PID controller made in python, see also http://www.csimn.com/CSI_pages/PIDforDummies.html
kp = 1.2
ki = 0.9
kd = 0.3
set_point = 50
prev_error = 0
cumulative_moving_average = 0
iteration = 0
def make_iteration(measured):
global iteration, set_point, prev_error, cumulative_moving_average
iteration += 1
err = measured - set_point
rate_of_change = prev_error - err
cumulative_moving_average = (err + (cumulative_moving_average * iteration)) / (iteration + 1)
integral = cumulative_moving_average * ki
derivative = rate_of_change * kd
proportional = err * kp
prev_error = err
return proportional + derivative + integral
max_iterations = 20
output = 0
for x in range(0, max_iterations):
output -= make_iteration(output)
print "Output is ", output
@lazyval
Copy link
Author

lazyval commented May 13, 2015

Here is the the run with up to date version of code:

etc :: ~/projects/pidpy » python pid.py
Output is  67.5
Output is  76.5
Output is  48.75
Output is  43.23
Output is  51.801
Output is  53.7821142857
Output is  50.7870610714
Output is  49.7090542857
Output is  50.4494564393
Output is  50.7451550424
Output is  50.4456404881
Output is  50.2572072706
Output is  50.2805271524
Output is  50.2966575719
Output is  50.252977221
Output is  50.2122907008
Output is  50.1953788273
Output is  50.1834786556
Output is  50.1677242618
Output is  50.1526264035

And here is what will happen if we'll replace cumulative sum with just sum of all previously seen errors:

etc :: ~/projects/pidpy » python pid.py
Output is  90.0
Output is  78.0
Output is  24.6
Output is  45.72
Output is  67.704
Output is  47.6328
Output is  41.16096
Output is  54.490272
Output is  53.7235104
Output is  46.29688128
Output is  49.117053696
Output is  52.4217113472
Output is  49.726585175
Output is  48.7117486049
Output is  50.5782290551
Output is  50.5489219216
Output is  49.4920173437
Output is  49.8523034167
Output is  50.3383303223
Output is  49.9743499009

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