-
Notifications
You must be signed in to change notification settings - Fork 38
/
sousvide.ino
1503 lines (1294 loc) · 40.9 KB
/
sousvide.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
*
* SousVideWith8SegmentDisplays
*
* Adaptative regulation sous-vide cooker algorithm
*
* See http://www.instructables.com/id/Cheap-and-effective-Sous-Vide-cooker-Arduino-power/ for more info
*
* Author : Etienne Giust - 2013, 2014
*
* Features
*
* - Works out of the box : no need for tweaking or tuning, the software adapts itself to the characteristics of your cooker : whether it is big, small, full of water, half-full, whether room temperature is low or high, it works.
* - Efficient regulation in the range of 0.5°C
* - Sound alarm warns when target temperature is reached
* - Automatic detection of lid opening and closing : regulation does not get mad when temperature probe is taken out of the water (which is a thing you need to do if you want to actually put food in your cooker)
* - Safety features :
* - automatic cut-off after 5 minutes of continuous heating providing no change in temperature
* - automatic cut-off after 24 hours of operation
* - automatic cut-off when temperature reaches 95 °C
* - allows target temperature only in the safe 50°c to 90°C range
* - Dead cheap and simple : no expensive LCD or Solid State Relay
*
*
* License
*
* Copyright (C) 2014 Etienne Giust
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
// ------------------------- PARTS NEEDED
// Arduino board
// integrated 8 digits led display with MAX7219 control module (3 wire interface)
// Pushbutton x 2
// Piezo element
// Waterproof DS18B20 Digital temperature sensor
// 4.7K ohm resistor
// 5V Relay module for Arduino, capable to drive AC125/250V at 10A
// Rice Cooker
// ------------------------- PIN LAYOUT
//
// inputs
// Pushbutton + on pin 6 with INPUT_PULLUP mode
// Pushbutton - on pin 5 with INPUT_PULLUP mode
// Temperature sensor on pin 9 (data pin of OneWire sensor)
// outputs
// Relay on pin 8
// Speaker (piezo) on pin 13
// 8 digit LED display DataIn on pin 12
// 8 digit LED display CLK on pin 11
// 8 digit LED display LOAD on pin 10
// ------------------------- LIBRARIES
#include <LedControl.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// ------------------------- CONSTANTS
// 8 segment display drivers
#define TEMP_DISPLAY_DRIVER 0
#define DISPLAY_LEFT 4 //left 4 digits of display
#define DISPLAY_RIGHT 0 //right 4 digits of display
#define REVERSE_DISPLAY 0 //set to 7 if your displays first digit is on the left
// push-buttons
#define BT_TEMP_MORE_PIN 6 //INPUT_PULLUP mode
#define BT_TEMP_LESS_PIN 5 //INPUT_PULLUP mode
// piezo
#define PIEZO_PIN 13
// temperature sensor
#define ONE_WIRE_BUS 9
#define TEMPERATURE_PRECISION 9
#define SAMPLE_DELAY 5000
#define OUTPUT_TO_SERIAL true
// relay
#define RELAY_OUT_PIN 8
// First Ramp
#define FIRST_RAMP_CUTOFF_RATIO 0.65
// Security features
#define MIN_TARGET_TEMP 50 /*sufficient for most sous-vide recipes*/
#define MAX_TARGET_TEMP 90 /*sufficient for most sous-vide recipes*/
#define SHUTDOWN_TEMP 95 /*shutdown if temp reaches that temp*/
#define MAX_UPTIME_HOURS 24 /*shutdown after 24 hours of operation*/
#define MAX_HEATINGTIME_NO_TEMP_CHANGE_MINUTES 5 /*detect when temp sensor is not in the water and prevent overheating*/
// regulation
#define MIN_SWITCHING_TIME 1500 /* Minimum ON duration of the heating element */
#define DROP_DEGREES_FOR_CALC_REGULATION 0.12 /* minimum drop in degrees used to calculate regulation timings (should be small : <0.2 ) */
#define LARGE_TEMP_DIFFERENCE 1 /* for more than "1" degree, use the Large setting (Small otherwise)*/
// ------------------------- DEFINITIONS & INITIALISATIONS
// buttons
int sw_tempMore;
int sw_tempLess;
// temperatures
double environmentTemp = 0;
double actualTemp = 0;
double targetTemp = 0;
double storedTargetTemp = 0;
double initialTemp = 0;
double firstRampCutOffTemp = 0;
double maxRegTEmp = 0;
double minRegTEmp = 0;
double tempBeforeDrop = 0;
double tempBeforeHeating = 0;
double parametersRegulationSetForTemp = 0;
double actualTempAtBoostStart = 0;
double expectedTempChange = 0;
double tempPreviousArray[6]= {0, 0, 0, 0, 0, 0};
// derivatives
double currentTempDerivative;
double previousDerivative;
// gains
double secondPerDegreeGainRef = 0;
double secondPerDegreeGainLarge = 0;
double secondPerDegreeGainSmall = 0;
// booleans & states
bool isNewSample = false;
boolean isWaitingForTempAlert = false;
boolean waitForSuddenRise = false;
boolean isDerivativeReliable = false;
boolean waitingForStabilization = false;
boolean doBackToFirstRampWhenStabilizing = false;
boolean isHeatOn = false;
boolean isCounteracting = false;
enum operatingState { INITIAL_WAIT = 0, TEMP_DROP, TEMP_RISE, FIRST_RAMP, BOOST_TEMP, COUNTER_FALL, WAIT_NATURAL_DROP, REGULATE};
operatingState opState = INITIAL_WAIT;
enum boostTypes {HIGHBOOST = 0, LOWBOOST};
boostTypes boostType = HIGHBOOST;
int warningsBeforeCounterFall;
// timings
unsigned long tcurrent = 0;
unsigned long tStartFirstRamp = 0;
unsigned long tStartBoostTemp = 0;
unsigned long tStartRealRegulation = 0;
unsigned long tFirstRampCutOff = 0;
unsigned long tEndFirstRamp = 0;
unsigned long tOperationalDelay = 0;
unsigned long burnupTime = 0;
unsigned long tMinReg = 0;
unsigned long tMaxReg = 0;
unsigned long tLastTurnOffRelay = 0;
unsigned long durationOnPulse = 0;
unsigned long durationOffPulse = 0;
unsigned long tGetTemperatureSample = 0;
unsigned long tCheckStabilize = 0;
unsigned long tCheckTakeOff = 0;
unsigned long tBackToLow = 0;
unsigned long tBackToHigh = 0;
unsigned long delaytime=100;
// security variables
unsigned long maxUptimeMillis;
unsigned long tCheckNotHeatingWildly;
// 7-segment and sensor variables
/*
LedControl :
pin 12 is connected to the DataIn
pin 11 is connected to the CLK
pin 10 is connected to LOAD
We have 1 MAX7219.
*/
LedControl lc=LedControl(12,11,10,1);
// Set up a oneWire instance and Dallas temperature sensor
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// variable to store temperature probe address
DeviceAddress tempProbeAddress;
// ------------------------- SETUP
void setup() {
Serial.begin(9600);
/*
Initialize MAX7219 display driver
*/
lc.shutdown(0,false);
lc.setIntensity(0,2);
lc.clearDisplay(0);
/*
Initialize pushButtons
*/
pinMode(BT_TEMP_MORE_PIN, INPUT_PULLUP);
pinMode(BT_TEMP_LESS_PIN, INPUT_PULLUP);
/*
Initialize temperature sensor
*/
sensors.begin();
delay(1000);
sensors.getAddress(tempProbeAddress, 0);
delay(1000);
sensors.requestTemperaturesByIndex(0); // Send the command to get temperatures
delay(1000);
/*
Read temperature
*/
actualTemp = sensors.getTempC(tempProbeAddress);
targetTemp = (long) ((int)actualTemp);
/*
Write initial values to display
*/
displayActualTemp(actualTemp);
displayTargetTemp(targetTemp);
//prepare Relay port for writing
pinMode(RELAY_OUT_PIN, OUTPUT);
digitalWrite(RELAY_OUT_PIN,LOW);
tcurrent = millis();
maxUptimeMillis = MAX_UPTIME_HOURS * (unsigned long)3600 * (unsigned long)1000;
// Initial State
warningsBeforeCounterFall = 3;
opState = INITIAL_WAIT;
delay(3000);
}
/**************************************************************************************/
/* */
/* MAIN LOOP */
/* */
/**************************************************************************************/
void loop() {
tcurrent = millis();
// get temperature every few seconds and output it to serial if needed. Alert if we are within range
GetTemperatureAndEnforceSecurity();
// compute current temperatue Derivative
SetActualDerivative();
switch (opState)
{
case INITIAL_WAIT:
// wait for initial temperature stability
if (abs(actualTemp - tempPreviousArray[1] ) < 0.1)
{
if (environmentTemp == 0)
{
// store initial temp, but not more than 30 degrees
environmentTemp = min(actualTemp, 30);
}
// check if target temp is in acceptable range and switch to first ramp if so
if(targetTemp >= MIN_TARGET_TEMP)
{
StartInitialRamping();
}
}
break;
case TEMP_DROP:
// wait for stabilization or for sudden rise
if (waitForSuddenRise == false && IsStabilizing())
{
if (abs(actualTemp - environmentTemp) < abs(actualTemp - tempBeforeDrop))
{
// we are close to environmentTemp. The temp probe is probably off-water; wait till temperature rises again sharply then stablilizes
waitForSuddenRise = true;
Serial.println("TEMP_DROP : wait temprise");
} else {
// something very cold was inserted in the cooker; or not. either way, the temp probe is back. let's regulate
if (doBackToFirstRampWhenStabilizing)
{
Serial.println("TEMP_RISE : initial ramping");
opState = FIRST_RAMP;
}
else
{
Serial.println(" TEMP_DROP : Cold ! reg");
EnterRegulateStateOrWaitSmoothLowering();
}
}
}
WatchForTempFalling();
break;
case TEMP_RISE:
// wait for stabilization, then Regulate
if ( IsStabilizingOrDropping() )
{
if (doBackToFirstRampWhenStabilizing)
{
Serial.println(" TEMP_RISE : back to initial ramping");
opState = FIRST_RAMP;
}
else
{
Serial.println(" TEMP_RISE : back to normal : reg");
EnterRegulateStateOrWaitSmoothLowering();
}
}
WatchForTempFalling();
break;
case FIRST_RAMP:
PerformFirstRamp();
break;
case COUNTER_FALL:
// START CONDITION : temp well below target && important negative derivative , but not freefall : -0.1 < d < -0.01, 3 times in a row
// ON, until deriv == 0 then cut and wait stabilization
if (isNewSample)
{
Serial.println(" Counterfall check");
if (waitingForStabilization == false)
{
// check derivative
//if(isDerivativeReliable && currentTempDerivative > -0.005)
double predicted = predictTemp(tOperationalDelay) ;
Serial.print(" predicted temp : ");
Serial.println(predicted);
if ( predicted >= (targetTemp - 1) && isDerivativeReliable && currentTempDerivative > 0.001) // targetTemp - 1 is to avoid overshoot because prediction is not precise enough
{
Serial.println(" TURNOFFRELAY !");
turnOffRelay();
waitingForStabilization = true;
}
}
else
{
if ( IsStabilizingOrDropping() )
{
Serial.println(" COUNTER_FALL finished : reg");
//reset counter
warningsBeforeCounterFall = 3;
EnterRegulateStateOrWaitSmoothLowering();
}
if( isDerivativeReliable && currentTempDerivative < -0.005)
{
turnOnRelay();
waitingForStabilization = false;
}
}
}
break;
case BOOST_TEMP:
PerformBoostTemp();
WatchForTempFalling();
break;
case WAIT_NATURAL_DROP:
if (isNewSample)
{
// when temp is close enough to target, try to calculate regulation values if they are not already set
if (isCounteracting == false && parametersRegulationSetForTemp != targetTemp && abs(actualTemp - targetTemp) < 3 )
{
PerformRegulationCalculations();
}
// predict temp at t + tOperationalDelay
double futureTemp = predictTemp(tOperationalDelay);
// counter act to stabilize near targetTemp
if (isCounteracting == false && futureTemp < targetTemp)
{
isCounteracting = true;
HeatForDegrees(actualTemp - futureTemp);
}
// check for stabilization
if ( ((long) (millis() - tCheckStabilize) >= 0) && isCounteracting )
{
if(IsStabilizingOrGrowing())
{
Serial.println("NATURAL_DROP ended: wait stabilize");
opState = TEMP_RISE; // make sure we stabilize before regulating again
}
if(IsAcceleratingFall())
{
Serial.println("fall:tryagain!");
isCounteracting = false;
}
}
// we fell too much
if (actualTemp < targetTemp - 0.1)
{
StartBoostToTarget();
}
}
WatchForTempFalling();
break;
case REGULATE:
Regulate();
WatchForTempFalling();
break;
}
if (opState != FIRST_RAMP && opState != COUNTER_FALL)
{
// check each time if relay needs to be turned off (except during initial ramping or counter action)
if ( (long) (millis() - tBackToLow) >= 0)
{
turnOffRelay();
}
}
// read buttons state
readButtonInputs();
// update displays
displayActualTemp(actualTemp);
displayTargetTemp(targetTemp);
// pause loop
delay(delaytime);
}
/**************************************************************************************/
/* */
/* HELPER FUNCTIONS */
/* */
/**************************************************************************************/
void ResetVariablesForRegulationCalculation()
{
maxRegTEmp = 0;
minRegTEmp = 1000;
}
void EnterRegulateStateOrWaitSmoothLowering()
{
if (actualTemp < targetTemp + 0.3)
{
Serial.println("EnterRegulateState !");
ResetVariablesForRegulationCalculation();
tBackToHigh = 0;
// make sure we do not start heating right away when entering regulation over target value
if (parametersRegulationSetForTemp == targetTemp && actualTemp > targetTemp )
{
tBackToHigh = millis() + durationOffPulse;
}
tBackToLow = 0;
tMinReg = 0;
tMaxReg = 0;
tStartRealRegulation = 0;
opState = REGULATE;
}
else
{
WaitForNaturalDrop();
}
}
void WaitForNaturalDrop()
{
opState = WAIT_NATURAL_DROP;
isCounteracting = false;
Serial.println("WAIT_NATURAL_DROP!");
ResetVariablesForRegulationCalculation();
}
void Regulate()
{
if (actualTemp > ( targetTemp + 0.2 ))
{
// adapt regul values : they are too high
if ( IsStabilizing() && parametersRegulationSetForTemp == targetTemp && tStartRealRegulation > 0 && (millis() - tStartRealRegulation) > tOperationalDelay )
{
durationOnPulse = durationOnPulse / 1.3;
while ( durationOnPulse < MIN_SWITCHING_TIME )
{
durationOffPulse = durationOffPulse * 1.2;
durationOnPulse = durationOnPulse * 1.2 ;
}
tStartRealRegulation = millis();
tBackToHigh = millis() + durationOffPulse;
Serial.print("durationOffPulse = ");
Serial.print(durationOffPulse);
Serial.print("durationOnPulse = ");
Serial.println(durationOnPulse);
WaitForNaturalDrop();
}
}
// try to regulate temperature when we are at a stable targetTemp
// Maybe we are far below the goal ; time for a boost ?
if((targetTemp - actualTemp) >= 0.25)
{
// adapt regul values : they are too low
if ( IsStabilizing() && parametersRegulationSetForTemp == targetTemp && (millis() - tStartRealRegulation) > tOperationalDelay )
{
durationOffPulse = durationOffPulse / 1.3;
while ( durationOffPulse < MIN_SWITCHING_TIME )
{
durationOffPulse = durationOffPulse * 1.2;
durationOnPulse = durationOnPulse * 1.2 ;
}
Serial.print("durationOffPulse = ");
Serial.print(durationOffPulse);
Serial.print(" durationOnPulse = ");
Serial.println(durationOnPulse);
}
StartBoostToTarget();
}
else
{
if (parametersRegulationSetForTemp == targetTemp )
{
if (tStartRealRegulation == 0)
{
tStartRealRegulation = millis();
tBackToHigh = 0;
}
// We already have ON and OFF durations
// perform regulation
if (digitalRead(RELAY_OUT_PIN) == LOW) {
// check if downtime over
if ( (long) (millis() - tBackToHigh) >= 0)
{
turnOnRelay();
tBackToLow = millis() + durationOnPulse + burnupTime;
tBackToHigh = millis() + durationOnPulse + burnupTime + durationOffPulse;
}
}
}
else
{
if ((targetTemp - actualTemp) >= 0.1)
{
//perform a boost with slight overshoot first
StartBoostToTarget(0.1);
}
else
{
// find suitable ON and OFF durations
PerformRegulationCalculations();
}
}
}
}
void PerformRegulationCalculations()
{
if (isNewSample && IsFallingNaturally() && tempPreviousArray[0] != 0 && tempPreviousArray[1] != 0 && tempPreviousArray[2] != 0)
{
// calc average of 3 last samples
double averageTemp3 = (tempPreviousArray[0] + tempPreviousArray[1] +tempPreviousArray[2]) / 3;
// find max and min temperatures
if (averageTemp3 > maxRegTEmp)
{
maxRegTEmp = averageTemp3;
tMaxReg = millis();
}
if (averageTemp3 < minRegTEmp)
{
minRegTEmp = averageTemp3;
tMinReg = millis();
}
Serial.print(" --- avgTemp3 = ");
Serial.print(averageTemp3, DEC);
Serial.print(" --- maxRegTEmp = ");
Serial.print(maxRegTEmp, DEC);
Serial.print(" --- minRegTEmp = ");
Serial.print(minRegTEmp, DEC);
Serial.print(" --- tMaxReg = ");
Serial.print(tMaxReg);
Serial.print(" --- tMinReg = ");
Serial.println(tMinReg);
// wait till we lost DROP_DEGREES_FOR_CALC_REGULATION degrees
if (maxRegTEmp > 0 && minRegTEmp > 0 && (((long)(tMinReg - tMaxReg)) > 0) && ((maxRegTEmp - minRegTEmp) > DROP_DEGREES_FOR_CALC_REGULATION))
{
// Try to come up with Pulse durations (ON and OFF) to counteract temperature loss
SetApproximatePulseDurationsForREgulation(maxRegTEmp - minRegTEmp, tMinReg - tMaxReg);
// back to target temp
StartBoostToTarget();
}
}
}
bool checkDerivativeReliable()
{
for(int i = 0; i < 6 ; i++)
{
if(tempPreviousArray[i]==0)
{
return false;
}
}
return true;
}
void SetActualDerivative()
{
if (isNewSample)
{
isDerivativeReliable = checkDerivativeReliable();
Serial.print("d = ");
if (isDerivativeReliable)
{
//remove biggest and lowest values (get rid off irregularities)
// identify lowest and highest
double lowest = 1000;
double highest = 0;
int i=0;
for(i=0;i<6;i++) {
if(tempPreviousArray[i] > highest)
highest = tempPreviousArray[i];
if(tempPreviousArray[i] < lowest)
lowest = tempPreviousArray[i];
}
double tempTemp[6];
double filteredValues[4];
bool isHighestRemoved = false;
bool isLowestRemoved = false;
//
if (currentTempDerivative > 0)
{
//ascending trend : remove lowest value to the end
for(i=5;i>=0;i--) {
if(tempPreviousArray[i] == lowest && !isLowestRemoved)
{
tempTemp[i] = 0;
isLowestRemoved = true;
} else {
tempTemp[i] = tempPreviousArray[i];
}
}
// remove highest value to the starts of the array
for(i=0;i<6;i++) {
if(tempTemp[i] == highest && !isHighestRemoved)
{
tempTemp[i] = 0;
isHighestRemoved = true;
}
}
}
else
{
//descending trend : remove lowest value to the starts of the array
for(i=0;i<6;i++) {
if(tempPreviousArray[i] == lowest && !isLowestRemoved)
{
tempTemp[i] = 0;
isLowestRemoved = true;
} else {
tempTemp[i] = tempPreviousArray[i];
}
}
// remove highest value to the end
for(i=5;i>=0;i--) {
if(tempTemp[i] == highest && !isHighestRemoved)
{
tempTemp[i] = 0;
isHighestRemoved = true;
}
}
}
int j = 0;
for(i=0;i<6;i++) {
if(tempTemp[i] != 0)
{
filteredValues[j] = tempTemp[i];
j++;
}
}
double pastValues[2];
pastValues[0] = ( filteredValues[0] + filteredValues[1] ) / 2;
pastValues[1] = ( filteredValues[2] + filteredValues[3] ) / 2;
// calculate last derivative
previousDerivative = currentTempDerivative;
currentTempDerivative = ((pastValues[0] - pastValues[1]) / (3* SAMPLE_DELAY/1000));
Serial.println(currentTempDerivative, DEC);
} else
{
Serial.println("NC!");
}
}
}
void GetTemperatureAndEnforceSecurity()
{
if ( (long) (tcurrent - tGetTemperatureSample) >= 0)
{
actualTemp = getTemperature();
if (opState != TEMP_DROP && (tempPreviousArray[0] - actualTemp > 2))
{
//sudden drop in temperature -> temp probe off-water
if(opState == COUNTER_FALL || opState == FIRST_RAMP)
{
tBackToLow = 0;
if (opState == FIRST_RAMP)
{
firstRampCutOffTemp = tempPreviousArray[0];
doBackToFirstRampWhenStabilizing = true;
}
}
opState = TEMP_DROP;
tempBeforeDrop = tempPreviousArray[0];
waitForSuddenRise = false;
Serial.println("REMOVED TEMP PROBE!");
if (tStartBoostTemp - millis() <= 3 * SAMPLE_DELAY)
{
// we probably boosted temp wrongly as temp probe was off-water
// cancel boost
tBackToLow = 0;
}
}
if (opState == TEMP_DROP && (actualTemp - tempPreviousArray[0] > 2))
{
//sudden rise in temperature -> temp probe back in water
opState = TEMP_RISE;
// erase previous values in history of temperature -> prevent calculated negative derivative even if we are climbing
tempPreviousArray[1]=0;
tempPreviousArray[2]=0;
tempPreviousArray[3]=0;
tempPreviousArray[4]=0;
tempPreviousArray[5]=0;
Serial.println("PROBE BACK");
}
if (opState == BOOST_TEMP && (actualTemp - tempPreviousArray[0] > 1))
{
//sudden rise in temperature during BOOST_TEMP -> maybe temp probe was just put back in water
if (tStartBoostTemp - millis() <= 3 * SAMPLE_DELAY)
{
// we probably boosted temp wrongly as temp probe was off-water
// cancel boost
tBackToLow = 0;
}
// erase previous values in history of temperature -> prevent calculated negative derivative even if we are climbing
tempPreviousArray[1]=0;
tempPreviousArray[2]=0;
tempPreviousArray[3]=0;
tempPreviousArray[4]=0;
tempPreviousArray[5]=0;
}
tempPreviousArrayPushValue(actualTemp);
isNewSample = true;
if (OUTPUT_TO_SERIAL) {
Serial.print(tcurrent/1000, DEC);
Serial.print("; ");
Serial.println(actualTemp, 3);
}
if (actualTemp > targetTemp + 0.15)
{
// force to turn off when no need to be ON (0.15 offset accounts for regulation conditions)
tBackToLow = 0;
}
alertTemperatureNearlySet();
checkShutdownConditions();
} else {
isNewSample = false;
}
}
void WatchForTempFalling()
{
if (isNewSample)
{
// START CONDITION : temp well below target && important negative derivative , but not freefall : -0.1 < d < -0.007, 3 times in a row
if ( (targetTemp - actualTemp) > 1 && IsFalling() )
{
// must happen 3 times in a row
warningsBeforeCounterFall--;
if (warningsBeforeCounterFall == 0)
{
turnOnRelay();
waitingForStabilization = false;
opState = COUNTER_FALL;
}
}
else
{
warningsBeforeCounterFall = 3;
}
}
}
void StartBoostToTarget()
{
StartBoostToTarget(0);
}
void StartBoostToTarget(double offset)
{
// predict value at t + tOperationalDelay
actualTempAtBoostStart = actualTemp;
double realTargetTemp = targetTemp + offset;
if (realTargetTemp > actualTempAtBoostStart)
{
expectedTempChange = realTargetTemp - actualTempAtBoostStart;
Serial.print("BOOST_TEMP! expectedTempChange = ");
Serial.println(expectedTempChange);
HeatForDegrees(expectedTempChange);
// change state
opState = BOOST_TEMP;
storedTargetTemp = targetTemp;
tStartRealRegulation = 0;
}
}
double HeatingTimeNeeded(double degreeOffset)
{
double secondPerDegreeGain;
if (degreeOffset > LARGE_TEMP_DIFFERENCE)
{
secondPerDegreeGain = secondPerDegreeGainLarge;
boostType = HIGHBOOST;
} else {
secondPerDegreeGain = secondPerDegreeGainSmall;
boostType = LOWBOOST;
}
return max(degreeOffset * secondPerDegreeGain * 1000, MIN_SWITCHING_TIME) + burnupTime;
}
void HeatForDegrees(double degrees)
{
if (degrees > 0)
{
tBackToLow = 0;
tCheckStabilize = 0;
tStartBoostTemp = millis();
tBackToLow = millis() + HeatingTimeNeeded(degrees);
tCheckStabilize = tBackToLow + tOperationalDelay;
if ( (long) (millis() - tBackToLow) < 0)
{
turnOnRelay();
Serial.print("HEAT ON ! tBackToLow = ");
Serial.println(tBackToLow, DEC);
Serial.print("tCheckStabilize = ");
Serial.println(tCheckStabilize);
}
}
}
void PerformBoostTemp()
{
if ( (long) (millis() - tBackToLow) >= 0)
{
//check if target temp changed and adapt timings
if (targetTemp > storedTargetTemp)
{
StartBoostToTarget();
}
// wait for stabilization
// perform following checks every SAMPLE_DELAY when we reached tOperationalDelay since the temperature boost was started
if ( ((long) (millis() - tCheckStabilize) >= 0) && isNewSample && isDerivativeReliable)
{
// check if stabilizing
if (IsStabilizingOrDropping())
{
Serial.println("STabilized !");
FinishBoostTemp();
}
}
} else {
// switch ON heat and wait for tBackToLow
if (digitalRead(RELAY_OUT_PIN) == LOW) {
turnOnRelay();
}
//check if target temp changed and adapt timings
if (targetTemp != storedTargetTemp)
{
double changeOffset = targetTemp - storedTargetTemp;
double newExpectedTempChange = expectedTempChange + changeOffset;
tBackToLow = tStartBoostTemp + HeatingTimeNeeded(newExpectedTempChange);
tCheckStabilize = tBackToLow + tOperationalDelay;
storedTargetTemp = targetTemp;
expectedTempChange = expectedTempChange + changeOffset;
Serial.print("target temp changed, new tBackToLow = ");
Serial.println(tBackToLow);
Serial.print("target temp changed, new expectedTempChange = ");
Serial.println(expectedTempChange);
}
}
}
void FinishBoostTemp()
{
AdaptGain(actualTemp);
Serial.println("FinishBoostTemp !");
// enter REGULATE state
EnterRegulateStateOrWaitSmoothLowering();
}
double predictTemp(unsigned long horizon)
{
double horizonSeconds = horizon/1000;
// compute predicted value
return ((( tempPreviousArray[0] + tempPreviousArray[1] + tempPreviousArray[2] ) / 3 ) + (currentTempDerivative * horizonSeconds));
}
void AdaptGain(double resultingTemp)
{
// only take account of ON_Durations > burnupTime and make sure we waited tOperationalDelay
unsigned long boostTempDuration = millis() - tStartBoostTemp;
unsigned long boostOnTempDuration = tLastTurnOffRelay - tStartBoostTemp;
if ( boostTempDuration > tOperationalDelay && boostOnTempDuration > burnupTime )
{
double gain;
if (boostType == LOWBOOST)
{
gain = secondPerDegreeGainSmall;
}
else
{
gain = secondPerDegreeGainLarge;
}
double actualTempChange = resultingTemp - actualTempAtBoostStart;
if (actualTempChange < (expectedTempChange / 5) )
{
gain = gain * 1.8;
}
else