Heater for threaded program

Dependents:   LEX_Threaded_Programming

Revision:
1:4435d407d827
Parent:
0:4e33cc8171f4
Child:
2:7f15386fcc90
--- a/Heater.cpp	Wed Jul 17 07:54:07 2019 +0000
+++ b/Heater.cpp	Wed Jul 17 13:00:41 2019 +0000
@@ -4,47 +4,73 @@
 
 
 ------------------------------------------------------------------------------*/
-
+#include "mbed.h"
+#include "MODSERIAL.h"
 #include "Heater.h"
 #include "ADS8568_ADC.h"
 
 extern ADS8568_ADC adc;
 extern float scale_factors[8];
 extern Timer timer;
-extern int MEAS_DELAY;
-extern int N_ROLL_AVG;
+extern DigitalIn adc_busy;
+extern MODSERIAL pc;  
+
 
     
 Heater::Heater(int i_port, int v_port, DigitalOut drive, float R_set)
-    :i_port(i_port),v_port(v_port),drive(drive), R_set(R_set){}
+    :R_set(R_set),i_port(i_port),v_port(v_port),drive(drive){}
 
 
 void Heater::read_R()
 {
+    //Reads R and then resets the drive back to its previous value
+    int i = 0;
+    int drive_prev = drive;
+    drive = 1;
+    wait_us(10);
+    adc.start_conversion(ALL_CH);
+    while(adc_busy == 1)
+        {
+            wait_us(1);
+            i++;
+        }
     adc.read_channels();
-    i = adc.read_channel_result(i_port)/scale_factors[i_port];
+            
+    drive = drive_prev;
+    //pc.printf("conversion took %d us\n", i );
+    i=0;
+    
+    
+    curr = adc.read_channel_result(i_port)/scale_factors[i_port];
     v = adc.read_channel_result(v_port)/scale_factors[v_port];
-    if (i != 0) R = v/i;
+    if (curr != 0) R = v/curr;
 }
 
 void Heater::hold(int hold_time)
 {
     int end_time = timer.read_ms() + hold_time;
-    while (int time = timer.read_ms() < end_time)
+    pc.printf("end time is %d \n",end_time);
+    float R_avg = 0;
+    while (timer.read_ms() < end_time)
     {
         drive = 1;
         wait_us(MEAS_DELAY);
         read_R();
-        while (float R_avg = ((N_ROLL_AVG-1)*R_avg + R)/N_ROLL_AVG > R_set)
+        R_avg = ((N_ROLL_AVG-1)*R_avg + R)/N_ROLL_AVG;
+        if (R_avg > R_set)
         {
             drive = 0;
-            wait_us(MEAS_DELAY);
-            read_R();
+            wait_us(2*MEAS_DELAY);
         }
+
     }
-}    
+}
+
 
 void Heater::Set_R_set(float R) {R_set = R;}
 
 float Heater::Get_R() {return R;}
 
+void Heater::turn_on () {drive = 1;}
+
+void Heater::turn_off () {drive = 0;}
\ No newline at end of file