Kyle Drain / Mbed 2 deprecated closed_loop_PI_controller

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
KDrainEE
Date:
Tue Mar 20 13:55:46 2018 +0000
Commit message:
Working PI control

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Mar 20 13:55:46 2018 +0000
@@ -0,0 +1,106 @@
+#include "mbed.h"
+#include <iostream>
+
+using namespace std;
+
+//constants
+const float scalar = 0.6;
+
+//ticker to compute output
+Ticker sample;
+
+//System IO
+AnalogIn setPoint(PTB0);
+AnalogIn speed(PTB2);
+PwmOut gateDrive(PTB1);
+
+//moving average filter
+float* samples;
+
+//PI controller
+double Input, Output, Setpoint;
+double errSum;
+double ITerm;
+double kp, ki;
+
+//saturation limits
+double outMin;
+double outMax;
+
+
+double sampling_frequency;
+double ti;
+
+void set_tunings(double KP, double KI)
+{
+    kp = KP;
+    ki = KI;
+}
+
+
+/*
+Length 8 moving average filter for noisy inputs
+*/
+float filter_input(AnalogIn input)
+{  
+    int filterLength = 8;
+   for(int i = filterLength -1; i > 0; i--)
+   {
+      samples[i] = samples[i-1]; 
+   }
+   samples[0] = input.read();
+   float sum = 0.0;
+   for(int j = 0; j < filterLength; j++)
+   {
+       sum += samples[j];
+   }
+   return sum/filterLength;   
+}
+
+void update_states()
+{
+    Input = speed.read();
+    Setpoint = filter_input(setPoint);
+//    Setpoint = setPoint.read();
+//   test step response
+//  Setpoint = 1/3.3;
+}
+
+void compute()
+{
+    //proportional
+    double error = Setpoint-Input;
+    
+    //integral
+    errSum +=(error * ti);//potentially the problem
+    ITerm = ki*errSum;
+    if(ITerm > outMax) ITerm = outMax;
+    if(ITerm < outMin) ITerm = outMin; 
+    
+    //compute output
+    Output = kp*error + ITerm;
+    if(Output > outMax) Output = outMax;
+    if(Output < outMin) Output = outMin;    
+}
+
+int main()
+{
+   outMin = 0.0;
+   outMax = 1.0;
+   
+   sampling_frequency = 1e3;
+   ti = 1/sampling_frequency;
+   
+   set_tunings(0.1414,19.7408);//Kp, Ki
+   
+   samples = new float[8];
+   
+   sample.attach(&compute, ti);
+   
+   while(true)
+   {
+    update_states();
+    gateDrive = scalar*Output;
+   }
+   
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Tue Mar 20 13:55:46 2018 +0000
@@ -0,0 +1,1 @@
+https://os.mbed.com/users/mbed_official/code/mbed/builds/aa5281ff4a02
\ No newline at end of file