Heater for threaded program

Dependents:   LEX_Threaded_Programming

Revision:
14:f266bf960b8d
Parent:
12:8a048f111140
Child:
15:e7838491c104
--- a/Heater.cpp	Tue Jul 23 09:41:53 2019 +0000
+++ b/Heater.cpp	Tue Jul 23 11:29:20 2019 +0000
@@ -27,7 +27,7 @@
 
 void Heater::output()
 {
-    pc.printf("%d,%f,%f,%f\n",timer.read_ms(),R_ref,R,drive.read());
+    pc.printf("%d,%f,%f,%f,%f\n",timer.read_ms(),R_ref,R,R_avg,drive.read());
 }
 
 void Heater::read()
@@ -35,7 +35,7 @@
     //Reads R and then resets the drive back to its previous value
     int i = 0;
 
-    int drive_prev = drive;     //Store previous value of drive
+    float drive_prev = drive.read();     //Store previous value of drive
     drive = 1;
     wait_us(MEAS_DELAY);        //Wait for ADC to settle
     adc.start_conversion(ALL_CH);
@@ -44,7 +44,7 @@
             wait_us(1);
             i++;
         }
-    drive = drive_prev;
+    drive.write(drive_prev);
     adc.read_channels();
 
             
@@ -58,11 +58,17 @@
     R = (float)v/curr;
     R_avg = (((N_ROLL_AVG - 1) * R_avg) + R)/N_ROLL_AVG;
 
-    error = R_ref - R;
+    error = R_ref - R_avg;
+    
+    //Avoid integral windup by limiting error past actuation saturation (actuator does saturate for any negative error, but  to ensure integrated error can decrease, the limit has been set to the negative of the positive limit
+    if (error*Kd > 1) {error = 1/Kd;}
+    else if (error*Kd < -1) {error = -1/Kd;}
+    
+    
     error_integrated += error;
     
     log_count++;
-    if (log_count > 2000)
+    if (log_count > 50)
     {
     log_count = 0;
     output();
@@ -84,7 +90,7 @@
         
         drive.write(Kd * error + Ki * error_integrated);
         wait_ms(WAIT_DELAY);  //Minimum duty cycle of 1%
-        pc.printf("%f,%f,%f\n",error,error_integrated,drive.read());
+        //pc.printf("%f,%f,%f\n",error,error_integrated,drive.read());
    
   
     }