-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1973 lines (1683 loc) · 54.9 KB
/
Copy pathmain.cpp
File metadata and controls
1973 lines (1683 loc) · 54.9 KB
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
/*
ESP32 TEC Bed-Cooler Controller — NETWORK CONTROL VERSION (no dial input)
HARDWARE REVISION (current sensors removed):
- 4x TEC via Cytron MD13S (PWM + DIR) -> unchanged
- ACS712 current sensors -> REMOVED
- Coolant temperature probe (2-wire NTC thermistor) -> NEW, on the pump block.
This is the regulated "water" temperature used by the PID loop.
- 2x DS18B20 (OneWire) -> glued to the TEC heatsinks,
for monitoring + heatsink over-temperature protection.
- PWM D5 pump (4 lead: 12V red/black power, PWM blue, tach green)
Pump runs ONLY when the water-level sensor reports the loop is full.
- XKC-Y26 non-contact water-level sensor -> NEW (submersion interlock)
- ST7789 TFT display, can be fully blanked from the settings menu (dark room).
*/
#include <Arduino.h>
#include <math.h>
#include <Preferences.h>
#include <WiFi.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <ESPmDNS.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Arduino_GFX_Library.h>
#ifndef BLACK
#define BLACK 0x0000
#endif
#ifndef WHITE
#define WHITE 0xFFFF
#endif
// ======================= USER HARDWARE CONFIG =======================
static const int NUM_TEC = 4;
static const int NUM_HEATSINK = 2; // DS18B20 sensors glued to the heatsinks
// Cytron MD13S control pins (PWM + DIR)
static const int TEC_PWM_PINS[NUM_TEC] = {25, 27, 32, 16};
static const int TEC_DIR_PINS[NUM_TEC] = {26, 14, 33, 17};
// DS18B20 heatsink sensors — each probe on its OWN dedicated OneWire bus/pin,
// so a flaky or mis-powered probe on one bus can't disturb the other. Each bus
// still needs its own 4.7k pull-up (DATA -> 3V3). GPIO15 is a strapping pin but
// its boot-default is HIGH, which is compatible with the pull-up.
static const int ONE_WIRE_PINS[NUM_HEATSINK] = {13, 15};
// Coolant temperature probe: 2-wire NTC thermistor on the pump block.
// Wiring of the divider: 3.3V --- NTC --- [ADC node] --- R_FIXED --- GND
static const int NTC_ADC_PIN = 34; // input-only ADC1 pin (was an ACS712 pin)
// PWM D5 pump
static const int PUMP_PWM_PIN = 19; // -> pump BLUE wire (PWM control input)
static const int PUMP_TACH_PIN = 22; // <- pump GREEN wire (tach / speed output)
// XKC-Y26 water-level sensor (YELLOW signal wire)
static const int WATER_LEVEL_PIN = 21;
// XKC-Y26 OUT is HIGH when liquid is detected (black MODE wire left floating =
// normally-open / positive output). Set false if you short MODE->GND (inverted).
static const bool WATER_LEVEL_ACTIVE_HIGH = true;
// TFT SPI pins
static const int TFT_SCK = 18;
static const int TFT_MOSI = 23;
static const int TFT_DC = 4;
// TFT backlight control (drives the BLK/BL pin). Lets us fully blank the panel
// for a dark room. Set to GFX_NOT_DEFINED if BL is hard-wired to 3V3.
// NOTE: GPIO15 is a boot strapping/JTAG pin and caused faint flicker when used
// for the backlight — use GPIO5 instead (free, safe as a normal output).
static const int TFT_BL = 5;
// If CS is tied to GND, keep GFX_NOT_DEFINED.
static const int TFT_CS = GFX_NOT_DEFINED;
// If you can wire RST to a GPIO, set it here. Otherwise keep GFX_NOT_DEFINED.
static const int TFT_RST = GFX_NOT_DEFINED;
// ST7789 170x320 + offsets
static const int TFT_NATIVE_W = 170;
static const int TFT_NATIVE_H = 320;
static const int TFT_COL_OFFSET_1 = 35;
static const int TFT_ROW_OFFSET_1 = 0;
static const int TFT_COL_OFFSET_2 = 35;
static const int TFT_ROW_OFFSET_2 = 0;
// Landscape orientation (should end up w=320 h=170)
static const int TFT_ROTATION = 1;
// IMPORTANT: lower SPI speed for stability
static const uint32_t TFT_SPI_SPEED = 8000000; // 8 MHz
// ======================= NTC CALIBRATION =======================
// Standard 10k NTC, beta 3950, with a 10k fixed resistor, supplied from 3.3V.
static const float NTC_SUPPLY_MV = 3300.0f;
static const float NTC_R_FIXED = 10000.0f; // fixed divider resistor (ohms)
static const float NTC_R0 = 10000.0f; // NTC resistance at 25C
static const float NTC_T0_K = 298.15f; // 25C in Kelvin
static const float NTC_BETA = 3950.0f;
// ======================= PUMP / TACH =======================
static const uint32_t PUMP_PWM_FREQ_HZ = 25000; // PC/D5 standard 25 kHz
static const uint8_t PUMP_PWM_RES_BITS = 8;
static const int PUMP_LEDC_CH = 4; // TECs use channels 0..3
static const float PUMP_TACH_PULSES_PER_REV = 2.0f;
static const float DEFAULT_PUMP_SPEED_PERCENT = 70.0f;
// ======================= CONTROL LIMITS =======================
static const float DEFAULT_MAX_POWER_PERCENT = 75.0f;
// Heatsink over-temperature protection (replaces the old overcurrent trip)
static const float HEATSINK_MAX_C = 70.0f;
static const float HEATSINK_CLEAR_C = 60.0f; // hysteresis for auto-clear
// PID defaults
static const float DEFAULT_KP = 30.0f;
static const float DEFAULT_KI = 2.0f;
static const float DEFAULT_KD = 10.0f;
// PWM (stable on ESP32): 20kHz @ 11-bit
static const uint32_t TEC_PWM_FREQ_HZ = 20000;
static const uint8_t TEC_PWM_RES_BITS = 11;
// Base direction level for COOL (can be inverted per channel)
static const bool COOL_DIR_LEVEL_HIGH = false;
// ======================= NETWORK SETTINGS =======================
static const char *AP_SSID = "TEC-CTRL-SETUP";
static const byte DNS_PORT = 53;
static const char *MDNS_HOST = "tec-ctrl"; // http://tec-ctrl.local/
// ======================= POLARITY DEFAULTS =======================
static const bool TEC_DIR_INVERT_DEFAULT[NUM_TEC] = {false, true, false, true};
// ======================= GLOBALS =======================
// Display
Arduino_DataBus *bus = new Arduino_ESP32SPI(
TFT_DC, TFT_CS, TFT_SCK, TFT_MOSI, GFX_NOT_DEFINED);
Arduino_GFX *gfx = new Arduino_ST7789(
bus,
TFT_RST,
TFT_ROTATION,
true,
TFT_NATIVE_W,
TFT_NATIVE_H,
TFT_COL_OFFSET_1, TFT_ROW_OFFSET_1,
TFT_COL_OFFSET_2, TFT_ROW_OFFSET_2);
// DS18B20 (heatsinks) — one sensor per dedicated bus.
static_assert(NUM_HEATSINK == 2, "per-bus DS18B20 wiring assumes exactly 2 sensors");
OneWire oneWire0(ONE_WIRE_PINS[0]);
OneWire oneWire1(ONE_WIRE_PINS[1]);
DallasTemperature dsBus0(&oneWire0);
DallasTemperature dsBus1(&oneWire1);
static DallasTemperature *const dsBus[NUM_HEATSINK] = {&dsBus0, &dsBus1};
static DeviceAddress hsAddr[NUM_HEATSINK];
static bool hsPresent[NUM_HEATSINK] = {false, false};
static int hsCount = 0;
static float heatsinkTempC[NUM_HEATSINK] = {NAN, NAN};
// Non-blocking heatsink temp conversion
static bool tempConvInFlight = false;
static uint32_t tempConvStartMs = 0;
static uint32_t lastTempKickMs = 0;
static const uint16_t tempConvDelayMs = 200; // 10-bit conversion ~187ms
// Coolant (NTC) temperature
static float waterTempC = NAN; // regulated coolant temp from the pump-block NTC
// Water level
static bool waterLevelOK = false; // debounced reading from the XKC-Y26 sensor
static bool waterLevelRawLast = false;
static uint32_t waterLevelChangeMs = 0;
// Software override: force the interlock to "water present" for bench testing
// (e.g. when the 5V sensor isn't powered yet). Defaults ON for testing.
static bool waterLevelOverride = true;
// Pump
static float pumpDutyApplied = 0.0f;
static volatile uint32_t pumpTachCount = 0;
static uint32_t lastTachSampleMs = 0;
static float pumpRpm = 0.0f;
// Preferences
Preferences prefs;
// Web
WebServer server(80);
DNSServer dnsServer;
static bool apMode = false;
static String staSSID = "";
static String staPASS = "";
static String staIP = "";
// Reboot scheduling
static bool rebootPending = false;
static uint32_t rebootAtMs = 0;
// System state
static bool systemOn = false;
static bool profileMode = false;
static float targetConstC = 20.0f;
static float profileC[24];
static float maxPowerPercent = DEFAULT_MAX_POWER_PERCENT;
// Pump + display settings (persisted)
static bool pumpEnabled = true;
static float pumpSpeedPercent = DEFAULT_PUMP_SPEED_PERCENT;
static bool displayOn = true;
static float kp = DEFAULT_KP;
static float ki = DEFAULT_KI;
static float kd = DEFAULT_KD;
static float targetTempC = NAN;
static float integralErr = 0.0f;
static float lastErr = 0.0f;
static uint32_t lastPidMs = 0;
static uint32_t profileStartMs = 0;
// Direction invert per TEC (runtime)
static bool dirInvert[NUM_TEC] = {false, false, false, false};
static float tecDutyApplied[NUM_TEC] = {0};
static uint32_t lastPowerChangeMs = 0;
// Fault
static bool faultTripped = false;
static String faultMsg;
static uint8_t overTempCount = 0;
// Manual test — any mix of channels can run at once, each at its own duty/
// direction, for one shared duration. Duty 0 means that channel stays off.
static bool manualActive = false;
static uint32_t manualEndMs = 0;
static float manualChanDuty[NUM_TEC] = {0};
static bool manualChanHeat[NUM_TEC] = {false};
// Display caching
struct DispCache
{
String waterLine;
String targetLine;
String levelLine;
String hsLine;
String ssidLine;
String ipLine;
bool fault = false;
String faultLine;
};
static DispCache dispLast;
static bool dispStaticDrawn = false;
static bool dispDirty = true;
static bool dispBlankedDrawn = false; // true once we've painted the OFF (black) state
// Layout (landscape 320x170)
static int W = 0, H = 0;
static const int M = 8;
static int waterValX, waterValY, waterValW, waterValH;
static int targetValX, targetValY, targetValW, targetValH;
static int levelX, levelY, levelW, levelH;
static int hsX, hsY, hsW, hsH;
static int ssidX, ssidY, ssidW, ssidH;
static int ipX, ipY, ipW, ipH;
static int faultY, faultH;
// ======================= HELPERS =======================
static inline float clampf(float v, float lo, float hi)
{
if (v < lo)
return lo;
if (v > hi)
return hi;
return v;
}
static uint16_t rgb565(uint8_t r, uint8_t g, uint8_t b)
{
return gfx->color565(r, g, b);
}
static String htmlEscape(const String &s)
{
String o;
o.reserve(s.length() + 16);
for (size_t i = 0; i < s.length(); i++)
{
char c = s[i];
if (c == '&')
o += "&";
else if (c == '<')
o += "<";
else if (c == '>')
o += ">";
else if (c == '"')
o += """;
else
o += c;
}
return o;
}
static void scheduleReboot(uint32_t msFromNow = 800)
{
rebootPending = true;
rebootAtMs = millis() + msFromNow;
}
static void resetPid()
{
integralErr = 0.0f;
lastErr = 0.0f;
lastPidMs = millis();
}
static void allTecOff();
static void setPump(float duty01);
// ======================= POLARITY SNIPPET =======================
static String invertSnippet()
{
String s = "static const bool TEC_DIR_INVERT_DEFAULT[4] = {";
for (int i = 0; i < NUM_TEC; i++)
{
if (i)
s += ", ";
s += (dirInvert[i] ? "true" : "false");
}
s += "};";
return s;
}
static void printInvertSnippetToSerial()
{
Serial.println("Paste into code to make polarity permanent:");
Serial.println(invertSnippet());
}
// ======================= SETTINGS (NVS) =======================
static void loadSettings()
{
prefs.begin("tecctrl", false);
systemOn = prefs.getBool("on", false);
profileMode = prefs.getBool("mode", false);
targetConstC = prefs.getFloat("tconst", 20.0f);
maxPowerPercent = prefs.getFloat("maxpwr", DEFAULT_MAX_POWER_PERCENT);
pumpEnabled = prefs.getBool("pumpen", true);
pumpSpeedPercent = prefs.getFloat("pumpspd", DEFAULT_PUMP_SPEED_PERCENT);
displayOn = prefs.getBool("dispon", true);
waterLevelOverride = prefs.getBool("wlovr", true);
for (int i = 0; i < NUM_TEC; i++)
dirInvert[i] = TEC_DIR_INVERT_DEFAULT[i];
for (int i = 0; i < NUM_TEC; i++)
{
String k = "inv" + String(i);
if (prefs.isKey(k.c_str()))
dirInvert[i] = prefs.getBool(k.c_str(), dirInvert[i]);
}
size_t n = prefs.getBytesLength("prof");
if (n == sizeof(profileC))
{
prefs.getBytes("prof", profileC, sizeof(profileC));
}
else
{
for (int i = 0; i < 24; i++)
profileC[i] = targetConstC;
prefs.putBytes("prof", profileC, sizeof(profileC));
}
kp = prefs.getFloat("kp", DEFAULT_KP);
ki = prefs.getFloat("ki", DEFAULT_KI);
kd = prefs.getFloat("kd", DEFAULT_KD);
prefs.end();
systemOn = false; // safety boot OFF
}
static void saveSettings()
{
prefs.begin("tecctrl", false);
prefs.putBool("on", systemOn);
prefs.putBool("mode", profileMode);
prefs.putFloat("tconst", targetConstC);
prefs.putFloat("maxpwr", maxPowerPercent);
prefs.putBool("pumpen", pumpEnabled);
prefs.putFloat("pumpspd", pumpSpeedPercent);
prefs.putBool("dispon", displayOn);
prefs.putBool("wlovr", waterLevelOverride);
for (int i = 0; i < NUM_TEC; i++)
{
String k = "inv" + String(i);
prefs.putBool(k.c_str(), dirInvert[i]);
}
prefs.putBytes("prof", profileC, sizeof(profileC));
prefs.putFloat("kp", kp);
prefs.putFloat("ki", ki);
prefs.putFloat("kd", kd);
prefs.end();
}
// WiFi creds
static bool loadWiFiCreds(String &ssid, String &pass)
{
prefs.begin("net", true);
ssid = prefs.getString("ssid", "");
pass = prefs.getString("pass", "");
prefs.end();
return ssid.length() > 0;
}
static void saveWiFiCreds(const String &ssid, const String &pass)
{
prefs.begin("net", false);
prefs.putString("ssid", ssid);
prefs.putString("pass", pass);
prefs.end();
}
// ======================= DS18B20 (HEATSINKS) =======================
static void printDeviceAddress(const DeviceAddress &addr)
{
for (uint8_t i = 0; i < 8; i++)
{
if (addr[i] < 16)
Serial.print("0");
Serial.print(addr[i], HEX);
}
}
static void setupDs18b20()
{
hsCount = 0;
for (int b = 0; b < NUM_HEATSINK; b++)
{
int pin = ONE_WIRE_PINS[b];
pinMode(pin, INPUT_PULLUP);
delay(5);
Serial.printf("Bus %d GPIO%d idle level (expect 1): %d\n", b, pin, digitalRead(pin));
dsBus[b]->begin();
int count = dsBus[b]->getDeviceCount();
Serial.printf("Bus %d DS18B20 count: %d parasite: %s\n", b, count,
dsBus[b]->isParasitePowerMode() ? "YES (check VDD wiring!)" : "no");
hsPresent[b] = false;
heatsinkTempC[b] = NAN;
if (count > 0 && dsBus[b]->getAddress(hsAddr[b], 0))
{
Serial.printf("Bus %d DS18B20 addr: ", b);
printDeviceAddress(hsAddr[b]);
Serial.println();
dsBus[b]->setResolution(hsAddr[b], 10);
dsBus[b]->setWaitForConversion(false);
hsPresent[b] = true;
hsCount++;
}
else
{
Serial.printf("Bus %d: no DS18B20 detected. Check wiring + 4.7k pull-up DATA->3V3.\n", b);
}
}
if (hsCount > 0)
{
for (int b = 0; b < NUM_HEATSINK; b++)
if (hsPresent[b])
dsBus[b]->requestTemperatures();
tempConvStartMs = millis();
tempConvInFlight = true;
lastTempKickMs = millis();
}
}
static void serviceHeatsinkTemps()
{
if (hsCount <= 0)
return;
uint32_t now = millis();
if (!tempConvInFlight)
{
if ((now - lastTempKickMs) >= 1000)
{
for (int b = 0; b < NUM_HEATSINK; b++)
if (hsPresent[b])
dsBus[b]->requestTemperatures();
tempConvStartMs = now;
tempConvInFlight = true;
}
return;
}
if ((now - tempConvStartMs) >= tempConvDelayMs)
{
lastTempKickMs = now;
tempConvInFlight = false;
for (int b = 0; b < NUM_HEATSINK; b++)
{
if (!hsPresent[b])
continue;
float t = dsBus[b]->getTempC(hsAddr[b]);
float newTemp = (t == DEVICE_DISCONNECTED_C) ? NAN : t;
if ((isnan(newTemp) != isnan(heatsinkTempC[b])) ||
(!isnan(newTemp) && fabsf(newTemp - heatsinkTempC[b]) > 0.1f))
{
heatsinkTempC[b] = newTemp;
dispDirty = true;
}
}
}
}
static float maxHeatsinkC()
{
float m = NAN;
for (int i = 0; i < NUM_HEATSINK; i++)
{
if (!isnan(heatsinkTempC[i]))
{
if (isnan(m) || heatsinkTempC[i] > m)
m = heatsinkTempC[i];
}
}
return m;
}
// ======================= COOLANT NTC PROBE =======================
static void serviceCoolantTemp()
{
const int samples = 16;
uint32_t sum = 0;
for (int k = 0; k < samples; k++)
sum += (uint32_t)analogReadMilliVolts(NTC_ADC_PIN);
float mv = (float)sum / (float)samples;
float newTemp;
// Out-of-range readings indicate an open or shorted probe.
if (mv < 50.0f || mv > (NTC_SUPPLY_MV - 50.0f))
{
newTemp = NAN;
}
else
{
// 3.3V -- NTC -- [node] -- R_FIXED -- GND
float rNtc = NTC_R_FIXED * ((NTC_SUPPLY_MV / mv) - 1.0f);
float tK = 1.0f / ((1.0f / NTC_T0_K) + (1.0f / NTC_BETA) * logf(rNtc / NTC_R0));
newTemp = tK - 273.15f;
}
if ((isnan(newTemp) != isnan(waterTempC)) ||
(!isnan(newTemp) && fabsf(newTemp - waterTempC) > 0.05f))
{
waterTempC = newTemp;
dispDirty = true;
}
}
// ======================= WATER LEVEL =======================
static void serviceWaterLevel()
{
bool raw = (digitalRead(WATER_LEVEL_PIN) == HIGH);
if (!WATER_LEVEL_ACTIVE_HIGH)
raw = !raw;
uint32_t now = millis();
if (raw != waterLevelRawLast)
{
waterLevelRawLast = raw;
waterLevelChangeMs = now;
}
// 250 ms debounce
if (raw != waterLevelOK && (now - waterLevelChangeMs) >= 250)
{
waterLevelOK = raw;
dispDirty = true;
}
}
// Effective interlock used by the pump/TEC logic. The override forces "water
// present" so the rig can run on the bench before the 5V sensor is wired.
static inline bool waterAvailable()
{
return waterLevelOverride || waterLevelOK;
}
// ======================= HEATSINK OVER-TEMP SAFETY =======================
static void serviceOverTemp()
{
float hot = maxHeatsinkC();
// Trip while running if a heatsink exceeds the limit.
if (!faultTripped && (systemOn || manualActive) && !isnan(hot) && hot >= HEATSINK_MAX_C)
{
if (overTempCount < 255)
overTempCount++;
if (overTempCount >= 3)
{
faultTripped = true;
faultMsg = "HEATSINK OVERTEMP (" + String(hot, 1) + "C)";
systemOn = false;
manualActive = false;
allTecOff();
saveSettings();
dispDirty = true;
}
}
else
{
overTempCount = 0;
}
}
static void serviceFaultAutoClear()
{
if (!faultTripped)
return;
if (systemOn || manualActive)
return;
// Clear once the heatsinks have cooled below the hysteresis threshold.
float hot = maxHeatsinkC();
if (isnan(hot) || hot <= HEATSINK_CLEAR_C)
{
faultTripped = false;
faultMsg = "";
overTempCount = 0;
dispDirty = true;
}
}
// ======================= TEC OUTPUT =======================
static void setTecOutput(int i, bool heatMode, float duty01)
{
duty01 = clampf(duty01, 0.0f, 1.0f);
bool coolLevel = COOL_DIR_LEVEL_HIGH;
if (dirInvert[i])
coolLevel = !coolLevel;
bool dirLevel = heatMode ? !coolLevel : coolLevel;
digitalWrite(TEC_DIR_PINS[i], dirLevel ? HIGH : LOW);
const int maxDuty = (1 << TEC_PWM_RES_BITS) - 1;
int dutyCounts = (int)lroundf(duty01 * (float)maxDuty);
dutyCounts = constrain(dutyCounts, 0, maxDuty);
ledcWrite(i, dutyCounts);
float prev = tecDutyApplied[i];
tecDutyApplied[i] = duty01;
if (fabsf(prev - tecDutyApplied[i]) > 0.02f)
dispDirty = true;
}
static void allTecOff()
{
for (int i = 0; i < NUM_TEC; i++)
setTecOutput(i, false, 0.0f);
}
// ======================= PUMP OUTPUT =======================
static void IRAM_ATTR pumpTachISR()
{
pumpTachCount++;
}
static void setPump(float duty01)
{
duty01 = clampf(duty01, 0.0f, 1.0f);
const int maxDuty = (1 << PUMP_PWM_RES_BITS) - 1;
int counts = (int)lroundf(duty01 * (float)maxDuty);
counts = constrain(counts, 0, maxDuty);
ledcWrite(PUMP_LEDC_CH, counts);
if (fabsf(pumpDutyApplied - duty01) > 0.02f)
dispDirty = true;
pumpDutyApplied = duty01;
}
// The pump may only spin when the loop is full (sensor submerged); running it
// dry can destroy the D5. It runs whenever the system (or a manual test) is
// active AND there is water AND no fault.
static void servicePump()
{
bool wantPump = pumpEnabled && waterAvailable() && !faultTripped && (systemOn || manualActive);
setPump(wantPump ? (pumpSpeedPercent / 100.0f) : 0.0f);
}
static void servicePumpTach()
{
uint32_t now = millis();
uint32_t dt = now - lastTachSampleMs;
if (dt < 1000)
return;
noInterrupts();
uint32_t c = pumpTachCount;
pumpTachCount = 0;
interrupts();
float rpm = (PUMP_TACH_PULSES_PER_REV > 0.0f)
? ((float)c * (60000.0f / (float)dt) / PUMP_TACH_PULSES_PER_REV)
: 0.0f;
lastTachSampleMs = now;
if (fabsf(rpm - pumpRpm) > 30.0f)
dispDirty = true;
pumpRpm = rpm;
}
// ======================= TARGETING =======================
static float computeProfileTarget(float &posHoursOut)
{
if (profileStartMs == 0)
profileStartMs = millis();
float elapsedHours = (millis() - profileStartMs) / 3600000.0f;
float h = fmodf(elapsedHours, 24.0f);
if (h < 0)
h += 24.0f;
int h0 = (int)floorf(h);
float frac = h - (float)h0;
int h1 = (h0 + 1) % 24;
posHoursOut = h;
float t0 = profileC[h0];
float t1 = profileC[h1];
return t0 * (1.0f - frac) + t1 * frac;
}
// ======================= PID CONTROL =======================
static void updateControl()
{
// TECs must never run without coolant flow: require water level OK.
if (faultTripped || !systemOn || !waterAvailable() || isnan(waterTempC) || manualActive)
{
if (!manualActive)
allTecOff();
resetPid();
return;
}
float posHours = NAN;
targetTempC = profileMode ? computeProfileTarget(posHours) : targetConstC;
uint32_t now = millis();
float dt = (now - lastPidMs) / 1000.0f;
if (dt <= 0.0f)
dt = 0.001f;
lastPidMs = now;
float err = targetTempC - waterTempC;
if ((err > 0 && lastErr < 0) || (err < 0 && lastErr > 0))
integralErr = 0.0f;
integralErr += err * dt;
float integralMax = (ki != 0.0f) ? (200.0f / ki) : 0.0f;
integralErr = clampf(integralErr, -integralMax, integralMax);
float deriv = (err - lastErr) / dt;
lastErr = err;
float output = kp * err + ki * integralErr + kd * deriv;
bool heatMode = (output > 0.0f);
float demandPercent = clampf(fabsf(output), 0.0f, maxPowerPercent);
float baseDuty = demandPercent / 100.0f;
for (int i = 0; i < NUM_TEC; i++)
setTecOutput(i, heatMode, baseDuty);
}
// ======================= MANUAL TEST =======================
// Start a manual test with a per-channel duty/direction. Any combination of
// channels can run together; duty 0 leaves that channel off. Each duty is
// clamped to the same Max-power limit the PID uses, so the test can never push
// a channel past the configured cap (set Max power, ask for 100% here, and the
// applied duty in /api/state reads back the cap).
static void startManualTest(const float duty[NUM_TEC], const bool heat[NUM_TEC], uint32_t durationMs)
{
float cap = maxPowerPercent / 100.0f;
for (int i = 0; i < NUM_TEC; i++)
{
manualChanDuty[i] = clampf(duty[i], 0.0f, cap);
manualChanHeat[i] = heat[i];
}
manualActive = true;
manualEndMs = millis() + durationMs;
systemOn = false;
resetPid();
allTecOff();
lastPowerChangeMs = millis();
dispDirty = true;
}
static void serviceManualTest()
{
if (!manualActive)
return;
// Stop the test on a fault or if the loop runs dry (TECs would overheat).
if (faultTripped || !waterAvailable())
{
manualActive = false;
allTecOff();
dispDirty = true;
return;
}
if ((int32_t)(millis() - manualEndMs) >= 0)
{
manualActive = false;
allTecOff();
lastPowerChangeMs = millis();
dispDirty = true;
return;
}
for (int i = 0; i < NUM_TEC; i++)
setTecOutput(i, manualChanHeat[i], manualChanDuty[i]);
}
// ======================= DISPLAY =======================
static void clearBox(int x, int y, int w, int h)
{
gfx->fillRect(x, y, w, h, BLACK);
}
static String truncateToFit(const String &s, int maxChars)
{
if ((int)s.length() <= maxChars)
return s;
if (maxChars <= 3)
return s.substring(0, maxChars);
return s.substring(0, maxChars - 3) + "...";
}
static void applyBacklight(bool on)
{
if (TFT_BL == GFX_NOT_DEFINED)
return;
digitalWrite(TFT_BL, on ? HIGH : LOW);
}
static void computeLayout()
{
W = gfx->width();
H = gfx->height();
waterValX = 120;
waterValY = 18;
waterValW = W - waterValX - M;
waterValH = 36;
targetValX = 120;
targetValY = 64;
targetValW = W - targetValX - M;
targetValH = 36;
levelX = M;
levelY = 108;
levelW = W - 2 * M;
levelH = 14;
hsX = M;
hsY = 124;
hsW = W - 2 * M;
hsH = 12;
ssidX = M;
ssidY = H - 24;
ssidW = W - 2 * M;
ssidH = 12;
ipX = M;
ipY = H - 12;
ipW = W - 2 * M;
ipH = 12;
faultH = 18;
faultY = H - faultH;
}
static void drawDisplayStatic()
{
dispStaticDrawn = true;
computeLayout();
gfx->fillScreen(BLACK);
gfx->setTextWrap(false);
gfx->setTextColor(WHITE);
gfx->setTextSize(2);
gfx->setCursor(M, 22);
gfx->print("WATER");
gfx->setCursor(M, 68);
gfx->print("TARGET");
gfx->drawLine(M, 58, W - M, 58, rgb565(40, 40, 40));
gfx->drawLine(M, H - 28, W - M, H - 28, rgb565(40, 40, 40));
dispLast = DispCache();
dispDirty = true;
}
static void drawDisplayDynamicIfNeeded()
{
// Display fully off (dark room): blank panel + backlight off, draw nothing.
if (!displayOn)
{
if (!dispBlankedDrawn)
{
gfx->fillScreen(BLACK);
applyBacklight(false);
dispBlankedDrawn = true;
dispStaticDrawn = false; // force full redraw when turned back on
}
return;
}
if (dispBlankedDrawn)
{
applyBacklight(true);
dispBlankedDrawn = false;
dispStaticDrawn = false;
}
if (!dispStaticDrawn)
drawDisplayStatic();
if (!dispDirty)
return;
String waterLine;
if (isnan(waterTempC))
waterLine = "PROBE?";
else
waterLine = String(waterTempC, 2) + "C";
float tgt = targetConstC;
if (profileMode)
{
float ph = NAN;
tgt = (systemOn ? computeProfileTarget(ph) : profileC[0]);
}
String targetLine = String(tgt, 2) + "C";
String levelLine;
if (waterLevelOverride)
levelLine = String("LEVEL: OVERRIDE (sns:") + (waterLevelOK ? "FULL)" : "LOW)");
else
levelLine = waterLevelOK ? "LEVEL: FULL" : "LEVEL: NEEDS WATER";
String hsLine = "HS ";
for (int i = 0; i < NUM_HEATSINK; i++)