-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdvanced-Water-Pump-Controller.ino
3795 lines (3538 loc) · 97 KB
/
Advanced-Water-Pump-Controller.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
/*
Advanced-Water-Pump-Controller.ino
Copyright (C) 2024 desiFish
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Hardware:
1. DOIT ESP32 DEVKIT V1
2. 128x64 OLED Display
3. DS1307 RTC
4. SCT Current sensor
5. AJ-SR04 Ultrasonic Sensor (Water Proof)
6. Float Sensor (Any)
NOT USING CURRENTLY--> ZMPT101B Voltage Sensor
*/
// For basic ESP32 stuff like wifi, OTA Update and Wifi Manager Server
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ElegantOTA.h>
// For Display and I2C
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SH110X.h>
#include "Fonts/FreeSerif9pt7b.h"
// Data Storage
#include <Preferences.h>
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include "RTClib.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
// RGB LED (2812B)
#include <FastLED.h>
// For SCT013 Current Sensor
#include "EmonLib.h"
// Google Sheet Logging
#include <HTTPClient.h>
EnergyMonitor emon1;
// PIN CONFIGURATIONS
#define BUTTON 15
// #define VOLTAGE_SENSOR 34
#define UltraRX 16 // to TX of sensor
#define UltraTx 17 // to RX of sensor
// SDA 21, SCL 22 used for I2C Devices
#define LED_PIN 4 // for WS2812B RGB LED
#define BUZZER_PIN 5
#define FLOAT_SENSOR 36
#define PUMP_PIN 2 // PUMP RELAY PIN
#define CURRENT_SENSOR_PIN 39 // SCT SENSOR PIN
// Output Devices
#define TURN_ON_RELAY digitalWrite(PUMP_PIN, HIGH) // update this
#define TURN_OFF_RELAY digitalWrite(PUMP_PIN, LOW) // update this
/*2 is 2 seconds, you can assign any time value you wish.
This is given because it takes a while for the current consumption to get stable.
And there are all sort of current and voltage spikes just after the pump is ON
Giving it few seconds should resolve it.*/
#define WAIT_AFTER_PUMP_ON 2
#define NUM_LEDS 1
// Define the array of leds
CRGB leds[NUM_LEDS];
// Create an instance of the HardwareSerial class for Serial 2
HardwareSerial uSonicSerial(2);
#define uSonic_BAUD 9600
#define MAX_ULTRASONIC_VALUE 400 // 400cm or 4meters or 4000 mm max distance read for this model (update accordingly)
#define TANK_VOLUME 950 // tank will never fill up to the brims due to sensors, for 1000 L I am reducing 50 L (approx) (update accordingly)
// Variables to hold sensor readings
byte percBegin;
byte percEnd;
// Variable to save current epoch time
String startTime, endTime;
Preferences pref;
RTC_DS1307 rtc;
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "asia.pool.ntp.org", 19800); // 19800 is offset of India, asia.pool.ntp.org is close to India 5.5*60*60
// your wifi name and password (used in preference)
String ssid;
String password;
AsyncWebServer server(80);
unsigned long ota_progress_millis = 0;
// Your Domain name with URL path or IP address with path
const char *serverName = "http://iotthings.pythonanywhere.com/api/pump_logs"; // this is my custum server which recieves the values from ESP32 and stores them in Google sheet
String apiKey;
// For Display
#define i2c_Address 0x3c // initialize with the I2C addr 0x3C Typically eBay OLED's
// #define i2c_Address 0x3d //initialize with the I2C addr 0x3D Typically Adafruit OLED's
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1 // QT-PY / XIAO
Adafruit_SH1106G display = Adafruit_SH1106G(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Wifi Manager HTML Code
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<title>Wi-Fi Manager</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html {
font-family: Arial, Helvetica, sans-serif;
display: inline-block;
text-align: center;
}
h1 {
font-size: 1.8rem;
color: white;
}
p {
font-size: 1.4rem;
}
.topnav {
overflow: hidden;
background-color: #0A1128;
}
body {
margin: 0;
}
.content {
padding: 5%;
}
.card-grid {
max-width: 800px;
margin: 0 auto;
display: grid;
grid-gap: 2rem;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
.card {
background-color: white;
box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5);
}
.card-title {
font-size: 1.2rem;
font-weight: bold;
color: #034078
}
input[type=submit] {
border: none;
color: #FEFCFB;
background-color: #034078;
padding: 15px 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
width: 100px;
margin-right: 10px;
border-radius: 4px;
transition-duration: 0.4s;
}
input[type=submit]:hover {
background-color: #1282A2;
}
input[type=text], input[type=number], select {
width: 50%;
padding: 12px 20px;
margin: 18px;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
label {
font-size: 1.2rem;
}
.value{
font-size: 1.2rem;
color: #1282A2;
}
.state {
font-size: 1.2rem;
color: #1282A2;
}
button {
border: none;
color: #FEFCFB;
padding: 15px 32px;
text-align: center;
font-size: 16px;
width: 100px;
border-radius: 4px;
transition-duration: 0.4s;
}
.button-on {
background-color: #034078;
}
.button-on:hover {
background-color: #1282A2;
}
.button-off {
background-color: #858585;
}
.button-off:hover {
background-color: #252524;
}
</style>
</head>
<body>
<div class="topnav">
<h1>Wi-Fi Manager</h1>
</div>
<div class="content">
<div class="card-grid">
<div class="card">
<form action="/wifi" method="POST">
<p>
<label for="ssid">SSID</label>
<input type="text" id ="ssid" name="ssid"><br>
<label for="pass">Password</label>
<input type="text" id ="pass" name="pass"><br>
<input type ="submit" value ="Submit">
</p>
</form>
</div>
</div>
</div>
</body>
</html>
)rawliteral";
// Search for parameter in HTTP POST request
const char *PARAM_INPUT_1 = "ssid";
const char *PARAM_INPUT_2 = "pass";
// variables tankLow for storing ultrasonic value for empty tank and tankFull for full level.
int tankLow, tankFull, liveTankLevel;
// variables ampLow for lowest safe level and ampMax for safe ampere max value.
float ampLow, ampMax;
float liveAmp, avgAmp;
int countAmp;
// pump status
bool isPumpRunning = false;
// float sensor status
bool floatSensor = false;
// using sensors or not
bool useUltrasonic, useSensors, useFloat, useWifi;
bool resetFlag = false, updateInProgress = false;
String errorCodeMessage[] = {"USR INTRPT", "TANK FULL", "HIGH AMPERE", "LOW AMPERE"};
// time and timer related variables
byte timeHour, timeMinute, timerHour = 0, timerMinute = 0, timerSecond = 0, timerCount = 0;
int onTime = 1230, offTime = 1330, lastDay;
bool doneForToday, autoRun;
String dateAndTime, onlyTime;
// for holding water level (in %)
byte holdData = 0;
// global error tracking variable, Core 0 updates it
byte raiseAlert = 0;
// display update frequency
unsigned long previousMillis = 0; // will store last time it was updated
long interval = 1000; // interval to wait (milliseconds)
// ultrasonic update frequency
unsigned long previousMillis1 = 0; // will store last time it was updated
long interval1 = 2000; // interval to wait (milliseconds)
// float update frequency
unsigned long previousMillis2 = 0; // will store last time it was updated
long interval2 = 1000; // interval to wait (milliseconds)
TaskHandle_t loop2Code;
// Elegant OTA related task
void onOTAStart()
{
// Log when OTA has started
updateInProgress = true;
FastLED.setBrightness(200);
leds[0] = CRGB::Red;
FastLED.show();
Serial.println("OTA update started!");
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(9, 10);
display.println("OTA UNDER PROGRESS");
display.display();
// <Add your own code here>
}
void onOTAProgress(size_t current, size_t final)
{
// Log
if (millis() - ota_progress_millis > 500)
{
ota_progress_millis = millis();
Serial.printf("OTA Progress Current: %u bytes, Final: %u bytes\n", current, final);
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(9, 10);
display.println("OTA UNDER PROGRESS");
display.setCursor(0, 25);
display.println("Done:");
display.print(current);
display.println(" bytes");
display.setCursor(0, 45);
display.println("Total:");
display.print(final);
display.println(" bytes");
display.display();
}
}
void onOTAEnd(bool success)
{
// Log when OTA has finished
if (success)
{
Serial.println("OTA update finished successfully!");
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(2, 10);
display.println("OTA UPDATE SUCCESSFUL");
display.display();
}
else
{
Serial.println("There was an error during OTA update!");
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(13, 10);
display.println("OTA UPDATE FAILED");
display.display();
}
// <Add your own code here>
updateInProgress = false;
}
// forward declaration
void drawTankLevel(byte);
void blinkOrange(byte, byte, int = 50);
void autoTimeUpdate(bool = true);
void pumpRunSequence(bool = false);
/**
* @brief Initializes the pump controller system
*
* This function sets up all necessary hardware components, loads settings,
* and prepares the system for operation.
*/
void setup(void)
{
Serial.begin(115200);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(PUMP_PIN, OUTPUT);
TURN_OFF_RELAY;
digitalWrite(BUZZER_PIN, HIGH);
delay(200);
digitalWrite(BUZZER_PIN, LOW);
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(20);
leds[0] = CRGB::Red;
FastLED.show();
pinMode(BUTTON, INPUT);
pref.begin("database", false);
display.begin(i2c_Address, true);
display.setContrast(0);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SH110X_WHITE);
display.setFont(&FreeSerif9pt7b);
display.setCursor(5, 15);
display.println("INITIALIZING");
display.setCursor(37, 35);
display.println("PUMP");
display.setCursor(0, 55);
display.println(" CONTROLLER");
display.display();
delay(500);
// loading preset values from the memory
if (!pref.isKey("tankLow"))
pref.putInt("tankLow", 0);
if (!pref.isKey("tankFull"))
pref.putInt("tankFull", 0);
if (!pref.isKey("ampLow"))
pref.putFloat("ampLow", 0.0);
if (!pref.isKey("ampMax"))
pref.putFloat("ampMax", 0.0);
if (!pref.isKey("useUltrasonic"))
pref.putBool("useUltrasonic", false);
if (!pref.isKey("useSensors"))
pref.putBool("useSensors", false);
if (!pref.isKey("useFloat"))
pref.putBool("useFloat", false);
if (!pref.isKey("useWifi"))
pref.putBool("useWifi", true);
if (!pref.isKey("apiKey"))
pref.putString("apiKey", "");
if (!pref.isKey("doneForToday"))
pref.putBool("doneForToday", false);
if (!pref.isKey("lastDay"))
pref.putInt("lastDay", 0);
if (!pref.isKey("autoRun"))
pref.putBool("autoRun", false);
tankLow = pref.getInt("tankLow", 0);
tankFull = pref.getInt("tankFull", 0);
ampLow = pref.getFloat("ampLow", 0);
ampMax = pref.getFloat("ampMax", 0);
useUltrasonic = pref.getBool("useUltrasonic", false);
useSensors = pref.getBool("useSensors", false);
useFloat = pref.getBool("useFloat", false);
useWifi = pref.getBool("useWifi", true);
apiKey = pref.getString("apiKey", "");
doneForToday = pref.getBool("doneForToday", false);
lastDay = pref.getInt("lastDay", 0);
autoRun = pref.getBool("autoRun", false);
if (!rtc.begin())
{
Serial.println("Couldn't find RTC");
Serial.flush();
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(34, 10);
display.println("RTC FAILED");
display.setTextColor(SH110X_BLACK, SH110X_WHITE);
display.setCursor(50, 41);
display.fillRect(47, 40, 29, 10, 1);
display.print("OKAY");
display.setTextColor(SH110X_WHITE);
display.display();
byte count = 0;
while (true)
{
if (digitalRead(BUTTON) == 1)
{
while (digitalRead(BUTTON) == 1)
{
delay(150);
count++;
}
if (count >= 1)
break;
}
}
}
if (autoRun)
{
DateTime now = rtc.now();
if (lastDay != now.day())
{ // if today is a different day, reset "doneForToday"
lastDay = now.day();
pref.putInt("lastDay", lastDay);
pref.putBool("doneForToday", false);
doneForToday = false;
}
}
leds[0] = CRGB::Yellow;
FastLED.show();
if (useWifi)
{
// wifi manager
bool wifiConfigExist = pref.isKey("ssid");
if (!wifiConfigExist)
{
pref.putString("ssid", "");
pref.putString("password", "");
}
ssid = pref.getString("ssid", "");
password = pref.getString("password", "");
if (ssid == "" || password == "")
{
Serial.println("No values saved for ssid or password");
// Connect to Wi-Fi network with SSID and password
Serial.println("Setting AP (Access Point)");
// NULL sets an open Access Point
WiFi.softAP("WIFI_MANAGER", "WIFImanager");
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
wifiManagerInfoPrint();
// Web Server Root URL
server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/html", index_html); });
server.on("/wifi", HTTP_POST, [](AsyncWebServerRequest *request)
{
int params = request->params();
for (int i = 0; i < params; i++) {
const AsyncWebParameter* p = request->getParam(i);
if (p->isPost()) {
// HTTP POST ssid value
if (p->name() == PARAM_INPUT_1) {
ssid = p->value();
Serial.print("SSID set to: ");
Serial.println(ssid);
pref.putString("ssid", ssid);
}
// HTTP POST pass value
if (p->name() == PARAM_INPUT_2) {
password = p->value();
Serial.print("Password set to: ");
Serial.println(password);
pref.putString("password", password);
}
//Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
}
}
request->send(200, "text/plain", "Done. Device will now restart.");
delay(3000);
ESP.restart(); });
server.begin();
WiFi.onEvent(WiFiEvent);
while (true)
;
}
WiFi.mode(WIFI_STA);
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname("PumpController");
WiFi.begin(ssid.c_str(), password.c_str());
Serial.println("");
display.clearDisplay();
display.setTextSize(1);
display.setCursor(5, 15);
display.println("WAITING FOR");
display.setCursor(30, 35);
display.println("WIFI TO");
display.setCursor(15, 55);
display.println(" CONNECT");
display.display();
// count variable stores the status of WiFi connection. 0 means NOT CONNECTED. 1 means CONNECTED
bool count = 1;
while (WiFi.waitForConnectResult() != WL_CONNECTED)
{
display.clearDisplay();
display.setCursor(10, 15);
display.println("COULD NOT");
display.setCursor(20, 35);
display.println("CONNECT");
display.display();
Serial.println("Connection Failed");
delay(2000);
// ESP.restart();
count = 0;
break;
}
if (count)
{
Serial.println(ssid);
Serial.println(WiFi.localIP());
display.clearDisplay();
display.setCursor(11, 15);
display.println("CONNECTED");
display.setCursor(15, 35);
display.println("IP ADDRESS");
display.setCursor(20, 55);
display.setFont(NULL);
display.println(WiFi.localIP());
display.display();
delay(4000);
display.clearDisplay();
display.setCursor(5, 15);
display.println("Setting");
display.setCursor(5, 35);
display.println("Server");
display.display();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(200, "text/plain", "Hi! Please add "
"/update"
" on the above address."); });
ElegantOTA.begin(&server); // Start ElegantOTA
// ElegantOTA callbacks
ElegantOTA.onStart(onOTAStart);
ElegantOTA.onProgress(onOTAProgress);
ElegantOTA.onEnd(onOTAEnd);
server.begin();
Serial.println("HTTP server started");
display.clearDisplay();
display.setCursor(5, 15);
display.println("Setting");
display.setCursor(5, 35);
display.println("Time");
display.display();
// RTC Update at startup
autoTimeUpdate(false);
}
}
pref.end();
// Start Serial 2 with the defined RX and TX pins and a baud rate of 9600
uSonicSerial.begin(uSonic_BAUD, SERIAL_8N1, UltraRX, UltraTx);
emon1.current(CURRENT_SENSOR_PIN, 27); // Current: input pin, calibration.
analogReadResolution(10); // read resolution (10=10 bits)
// create a task that will be executed in the loop2() function, with priority 1 and executed on core 0
xTaskCreatePinnedToCore(
loop2, // Task function.
"loop2Code", // name of task.
10000, // Stack size of task
NULL, // parameter of the task
1, // priority of the task
&loop2Code, // Task handle to keep track of created task
0); // pin task to core 0
}
/**
* @brief Secondary core loop for sensor monitoring and safety checks
*
* @param pvParameters Pointer to task parameters (unused in this implementation)
*
* This function runs continuously on Core 0, handling real-time sensor monitoring
* and safety-critical operations.
*/
void loop2(void *pvParameters)
{
for (;;)
{
if (useSensors)
liveAmp = readAmpere();
delay(10);
if (useFloat)
floatSensor = readFloat(); // reads float sensor value and updates it
delay(10);
if (useUltrasonic)
liveTankLevel = readUltrasonic();
delay(10);
if (isPumpRunning)
{
raiseAlert = intelligentMonitoring();
Serial.print("PUMP RUN ERRORCODE");
Serial.println(": " + String(raiseAlert));
}
delay(10);
DateTime now = rtc.now();
timeHour = now.hour();
timeMinute = now.minute();
dateAndTime = now.timestamp(DateTime::TIMESTAMP_FULL);
onlyTime = now.timestamp(DateTime::TIMESTAMP_TIME);
if (isPumpRunning)
{
byte sec = now.second();
if (timerCount != sec)
{
timerCount = sec;
timerSecond++;
if (timerSecond > 59)
{
timerSecond = 0;
timerMinute++;
avgAmp += liveAmp;
countAmp++;
if (timerMinute > 59)
{
timerMinute = 0;
timerHour++;
if (timerHour > 23)
timerHour = 0;
}
}
}
}
if (autoRun && !doneForToday && !isPumpRunning)
{
bool flag = checkTimeFor(onTime, offTime);
if (flag)
{
raiseAlert = 99; // special case for automatic pump start
doneForToday = true;
}
}
delay(10);
}
}
/**
* @brief Main loop for user interface and non-critical operations
*
* This function runs on Core 1, managing the user interface, display updates,
* and other non-critical tasks.
*/
void loop(void)
{
// no OTA when pump is running
if (!isPumpRunning && useWifi)
ElegantOTA.loop();
if (raiseAlert > 1 && raiseAlert < 5)
{
errorMsg(raiseAlert, true);
raiseAlert = 0;
}
else if (raiseAlert == 99)
runPumpAuto();
if (!updateInProgress)
{
if (resetFlag) // after resetting (set in menu options; reset), esp32 will restart
{
leds[0] = CRGB::Red;
FastLED.show();
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(5, 20);
display.println("PUMP CONTROLLER WILL");
display.setCursor(5, 40);
display.print("RESTART NOW");
display.display();
delay(3000);
ESP.restart();
}
leds[0] = CRGB::Black;
FastLED.show();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
display.clearDisplay();
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(5, 1);
display.print(onlyTime);
display.setCursor(60, 1);
if (isPumpRunning)
{
display.println("PUMP: ON");
leds[0] = CRGB::Purple;
FastLED.show();
}
else if (!doneForToday)
{
display.println("PUMP: OFF");
leds[0] = CRGB::White;
FastLED.show();
}
else
{
display.println("PUMP: OFF");
leds[0] = CRGB::Green;
FastLED.show();
}
if (useUltrasonic)
drawTankLevel(tankLevelPerc());
vitals();
display.display();
}
}
// long press to activate menu
byte count = 0;
if (digitalRead(BUTTON) == 1)
{
while (digitalRead(BUTTON) == 1)
{
count++;
if (count >= 1 && count <= 30)
{
blinkOrange(1, 20, 50);
}
else
{
blinkOrange(0, 150, 0);
delay(100);
}
delay(50);
}
FastLED.setBrightness(20);
leds[0] = CRGB::Black;
FastLED.show();
if (count >= 1 && count <= 30)
{
leds[0] = CRGB::Yellow;
FastLED.show();
pumpRunSequence();
}
else
menu();
}
}
/**
* @brief Initiates or stops the pump operation with safety checks
*
* @param flag If true, initiates auto-run mode
*
* This function handles the pump start/stop sequence, including user confirmation
* and safety checks before operation.
*/
void pumpRunSequence(bool flag)
{
delay(100);
byte count = 0, option = 1;
while (true)
{
if (isPumpRunning)
{
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(30, 10);
display.println("STOP PUMP?");
// buttons
if (option == 1)
{
display.setCursor(20, 40);
display.print("YES");
display.setCursor(90, 40);
display.fillRect(88, 39, 15, 10, 1);
display.setTextColor(SH110X_BLACK, SH110X_WHITE);
display.print("NO");
display.setTextColor(SH110X_WHITE);
}
else
{
display.setCursor(20, 40);
display.fillRect(18, 39, 21, 10, 1);
display.setTextColor(SH110X_BLACK, SH110X_WHITE);
display.print("YES");
display.setTextColor(SH110X_WHITE);
display.setCursor(90, 40);
display.print("NO");
}
if (digitalRead(BUTTON) == 1)
{
while (digitalRead(BUTTON) == 1)
{
count++;
if (count >= 1 && count <= 8)
{
blinkOrange(1, 20);
}
else
{
blinkOrange(0, 150);
delay(100);
}
delay(50);
}
FastLED.setBrightness(20);
leds[0] = CRGB::Black;
FastLED.show();
if (count >= 1 && count <= 8)
{
option++;
if (option > 2)
option = 1;
}
else
{
if (option == 1)
break;
else if (option == 2)
{
if (isPumpRunning)
{ // check if pump is running
isPumpRunning = false;
TURN_OFF_RELAY;
delay(200);
if (useWifi)
{
endTime = onlyTime;
percEnd = tankLevelPerc();
pumpLog(errorCodeMessage[0]);
}
timerReset();
}
break;
}
}
}
count = 0;
display.display();
}
else
{
display.clearDisplay();
display.setTextColor(SH110X_WHITE);
display.setTextSize(1);
display.setFont(NULL);
display.setCursor(30, 10);
display.println("START PUMP?");
// buttons
if (option == 1)
{
display.setCursor(20, 40);
display.print("YES");
display.setCursor(90, 40);
display.fillRect(88, 39, 15, 10, 1);
display.setTextColor(SH110X_BLACK, SH110X_WHITE);
display.print("NO");
display.setTextColor(SH110X_WHITE);
}
else
{
display.setCursor(20, 40);
display.fillRect(18, 39, 21, 10, 1);
display.setTextColor(SH110X_BLACK, SH110X_WHITE);
display.print("YES");
display.setTextColor(SH110X_WHITE);
display.setCursor(90, 40);
display.print("NO");
}
if (flag || digitalRead(BUTTON) == 1)
{
while (digitalRead(BUTTON) == 1)
{
count++;
if (count >= 1 && count <= 8)
{
blinkOrange(1, 20);
}
else
{
blinkOrange(0, 150);