Nikita Klimchuk / Mbed 2 deprecated PID_new_temp

Dependencies:   mbed millis

Revision:
0:2b302a1ce68a
Child:
1:36155a9a4422
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/PID.cpp	Tue Dec 15 07:52:00 2020 +0000
@@ -0,0 +1,96 @@
+#include "mbed.h"
+#include "millis.h"
+//#include "SoftwarePWM.h"
+//#include "USBDevice.h"
+#define threshold 0.009 // 1/330
+unsigned long lastTime;
+double Input, Output;
+double Setpoint=0.10606060606; //35/330;
+double errSum, lastErr;
+double kp, ki, kd;
+int SampleTime = 1000; //1 sec
+
+
+AnalogIn temperature(p20);
+PwmOut fanControl(p21);
+//static BufferedSerial pc(USBTX, USBRX);
+
+Ticker temperatureTicker;
+
+int readTemperatureFlag=0;
+
+void tickerFlagOn()
+{
+    //led2 = !led2;
+    readTemperatureFlag=1;
+}
+
+void Compute()
+{   
+    printf("PID is functioning\n\r");
+   unsigned long now = millis();
+   int timeChange = (now - lastTime);
+    //if(timeChange>=SampleTime)
+    //{
+      /*Compute all the working error variables*/
+      double error = Setpoint - Input;
+      errSum += error;
+      double dErr = (error - lastErr);
+ 
+      /*Compute PID Output*/
+      Output = kp * error + ki * errSum + kd * dErr;
+ 
+      /*Remember some variables for next time*/
+      lastErr = error;
+      lastTime = now;
+    //}
+   //printf("PID loop has ended\n\r");
+}
+ 
+void SetTunings(double Kp, double Ki, double Kd)
+{
+  double SampleTimeInSec = ((double)SampleTime)/1000;
+   kp = Kp;
+   ki = Ki * SampleTimeInSec;
+   kd = Kd / SampleTimeInSec;
+}
+ 
+void SetSampleTime(int NewSampleTime)
+{
+   if (NewSampleTime > 0)
+   {
+      double ratio  = (double)NewSampleTime
+                      / (double)SampleTime;
+      ki *= ratio;
+      kd /= ratio;
+      SampleTime = (unsigned long)NewSampleTime;
+   }
+}
+int main()
+{
+    
+    float oldTemperature = temperature.read();
+    float newTemperature= oldTemperature;
+    temperatureTicker.attach(&tickerFlagOn, 0.2); // the address of the function to be attached (tickerFlagOn) and the interval (0.2 seconds)
+    
+    while (1)
+    {
+        newTemperature = temperature.read();
+           //  if ((newTemperature < (oldTemperature-threshold)) || (newTemperature > (oldTemperature+threshold)))
+            // {
+                oldTemperature = newTemperature; // These are for the threshold
+                printf("Temperature= %.1f degrees\n\r", 3.3*oldTemperature*100);
+           //  }
+    //Setpoint=0.0757575757575758;
+    //Setpoint=25/330;
+    Input=oldTemperature;
+    SetTunings(4, 2, 1);
+    Compute();
+    fanControl.period(0.00004f); 
+    if (Setpoint<Input)fanControl.write(-Output); else fanControl.write(0);
+    //fanControl.write(0.50f);
+    printf("inp %f set %f out %f \n \r", Input, Setpoint, Output); 
+    wait(3); 
+    }
+    
+}
\ No newline at end of file