So, I have the below code running in an ESP8266. This is for an IoT plant watering system. In my website I have the soil moisture indication, Auto/Timer switch and calibration.
For Auto mode, I have indication for actual soil moisture and option to set desired soil moisture. When actual fall below set value, I get output to diver a pump.
For Timer mode, I can set watering at fixed intervals without monitoring the actual soil moisture.
For calibration, I can enter the values for mapping 0-100%. There is also a Calibration ON/OFF switch. When this switch is ON, the reading should update every 2 seconds. When this switch is off, reading is updated every 60 seconds.
Below is my code. The problem is , it only reads the calibration ON/OFF state and does not run theough other cases. I am attaching the code and also what I see in my Serial monitor below. Seeking expert help to resolve the issue
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
static const uint8_t D0 = 16;
static const uint8_t D1 = 5;
static const uint8_t D2 = 4;
static const uint8_t D3 = 0;
static const uint8_t D4 = 2;
static const uint8_t D5 = 14;
static const uint8_t D6 = 12;
static const uint8_t D7 = 13;
static const uint8_t D8 = 15;
static const uint8_t D9 = 3;
static const uint8_t D10 = 1;
int device1_pin = D5;
int device2_pin = D6;
int device3_pin = D7;
int device4_pin = D8;
const int numReadings = 20;
const char* host = "<MYWEBSITE>.com";
const int sensor_pin = A0; /* Connect Soil moisture analog sensor pin to A0 of NodeMCU */
int readings[numReadings]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
int inputPin = A0;
int cal_status;
unsigned long time_now = 0;
int SetValueInWebPage;
int ActualSensorValueInWebPage;
int timermode;
int CheckCalibrationMode;
int Cal_HighValueInWebsite;
int Cal_LowValueInWebsite;
unsigned long TimerPeriodSetInWebsite;
unsigned long SwitchOnDurationInTimerMode;
unsigned long CalibrationModeON_Time = 2000;
unsigned long CalibrationModeOFF_Time = 60000;
unsigned long CalibrationModeON_TimeStamp;
unsigned long CalibrationModeOFF_TimeStamp;
unsigned long SwitchOnDurationInAutoMode = 5000;
unsigned long SoakDurationInAutoMode = 65000;
unsigned long MyHTTPrequestTimer = 0;
const byte CheckMode = 10;
const byte CheckValue = 15;
const byte AutoModeSwitchOn = 20;
const byte TimerModeSwitchOn = 30;
const byte OnOffTiming = 35;
const byte switchOn = 40;
const byte WaitForAutoModeOnTimeToEnd = 45;
const byte WaitForTimerONTime_End = 50;
const byte Timer_Start_OFF_Period = 55;
const byte WaitForTimerOFF_PeriodToEnd = 60;
const byte WaitForTimerDurationToEnd = 65;
const byte WaitForSoakTimeToEnd = 70;
const byte SoakTimeStartOff = 75;
const byte CalibrationModeON = 80;
const byte CalibrationModeOFF = 85;
const byte CalibrationModeON_Wait = 90;
const byte CalibrationModeOFF_Wait = 95;
unsigned long OFFPeriodStartsTimestamp;
unsigned long SwitchOnTimeStamp;
unsigned long TimerModeOnTimeStamp;
unsigned long SoakTimeStamp;
byte MyStateVariable;
boolean TimePeriodIsOver (unsigned long &periodStartTime, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - periodStartTime >= TimePeriod )
{
periodStartTime = currentMillis; // set new expireTime
return true; // more time than TimePeriod) has elapsed since last time if-condition was true
}
else return false; // not expired
}
unsigned long MyTestTimer = 0;
void ShowActualState() {
Serial.print("MyStateVariable is on value: ");
if (MyStateVariable == CheckMode) {
Serial.print("CheckMode (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == CheckValue) {
Serial.print("CheckValue (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == AutoModeSwitchOn) {
Serial.print("AutoModeSwitchOn (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == TimerModeSwitchOn) {
Serial.print("TimerModeSwitchOn (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == OnOffTiming) {
Serial.print("OnOffTiming (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == switchOn) {
Serial.print("switchOn (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == WaitForAutoModeOnTimeToEnd) {
Serial.print("WaitForAutoModeOnTimeToEnd (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == WaitForTimerONTime_End) {
Serial.print("WaitForTimerONTime_End (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == Timer_Start_OFF_Period) {
Serial.print("Timer_Start_OFF_Period (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == WaitForTimerOFF_PeriodToEnd) {
Serial.print("WaitForTimerOFF_PeriodToEnd (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == WaitForTimerDurationToEnd) {
Serial.print("WaitForTimerDurationToEnd (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == WaitForSoakTimeToEnd) {
Serial.print("WaitForSoakTimeToEnd (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == SoakTimeStartOff) {
Serial.print("SoakTimeStartOff (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == CalibrationModeON) {
Serial.print("CalibrationModeON (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == CalibrationModeOFF) {
Serial.print("CalibrationModeOFF (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == CalibrationModeON_Wait) {
Serial.print("CalibrationModeON_Wait (");
Serial.print(MyStateVariable);
Serial.println(")");
}
if (MyStateVariable == CalibrationModeOFF_Wait) {
Serial.print("CalibrationModeOFF_Wait (");
Serial.print(MyStateVariable);
Serial.println(")");
}
}
void setup () {
Serial.begin(115200);
WiFiManager wifiManager;
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings[thisReading] = 0;
}
if (WiFi.SSID() != "") wifiManager.setConfigPortalTimeout(60); //If no access point name has been previously entered disable timeout. Else timeout 60s
Serial.print("Connecting to ");
wifiManager.autoConnect("Device");
Serial.println("Connected to WiFi");
pinMode(device1_pin, OUTPUT);
pinMode(device2_pin, OUTPUT);
pinMode(device3_pin, OUTPUT);
pinMode(device4_pin, OUTPUT);
MyStateVariable = CheckMode;
}
void loop() {
// subtract the last reading:
total = total - readings[readIndex];
// read from the sensor:
readings[readIndex] = analogRead(inputPin);
// add the reading to the total:
total = total + readings[readIndex];
// advance to the next position in the array:
readIndex = readIndex + 1;
// if we're at the end of the array...
if (readIndex >= numReadings) {
// ...wrap around to the beginning:
readIndex = 0;
}
// calculate the average:
average = total / numReadings;
// send it to the computer as ASCII digits
//Serial.println(average);
// visual feedback with the help of the onboard-led if loop is running
//BlinkHeartBeatLED(OnBoard_LED, 500);
unsigned long currentMillis = millis();
if ( TimePeriodIsOver(MyHTTPrequestTimer, 5000) ) {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_calmode.php?did=1"); //Specify request destination
int httpCode1 = http.GET(); //Send the request
if (httpCode1 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
CheckCalibrationMode = payload.toInt();
Serial.println();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_calL.php?did=1"); //Specify request destination
int httpCode2 = http.GET(); //Send the request
if (httpCode2 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Cal_LowValueInWebsite = payload.toInt();
Serial.print("Cal Low Value=");
Serial.print(Cal_LowValueInWebsite); //Print the response payload
Serial.println();
}/////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_calH.php?did=1"); //Specify request destination
int httpCode3 = http.GET(); //Send the request
if (httpCode3 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Cal_HighValueInWebsite = payload.toInt();
Serial.print("Cal High Value=");
Serial.print(Cal_HighValueInWebsite); //Print the response payload
Serial.println();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_set.php?did=1"); //Specify request destination
int httpCode4 = http.GET(); //Send the request
if (httpCode4 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
SetValueInWebPage = payload.toInt();
Serial.print("Set Moisture=");
Serial.print(SetValueInWebPage); //Print the response payload
Serial.println();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_act.php?did=1"); //Specify request destination
int httpCode5 = http.GET(); //Send the request
if (httpCode5 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
ActualSensorValueInWebPage = payload.toInt();
Serial.print("Actual Moisture=");
Serial.print(ActualSensorValueInWebPage); //Print the response payload
Serial.println();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_timer.php?did=1"); //Specify request destination
int httpCode6 = http.GET(); //Send the request
if (httpCode6 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
TimerPeriodSetInWebsite = payload.toInt();
Serial.print("Set Timer=");
Serial.print(TimerPeriodSetInWebsite); //Print the response payload
Serial.println();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_dur.php?did=1"); //Specify request destination
int httpCode7 = http.GET(); //Send the request
if (httpCode7 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
SwitchOnDurationInTimerMode = payload.toInt();
Serial.print("Set Duration=");
Serial.print(SwitchOnDurationInTimerMode); //Print the response payload
Serial.println();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
http.begin("http://<MYWEBSITE><MYWEBSITEADDRESS>/fetch_timermode.php?did=1"); //Specify request destination
int httpCode8 = http.GET(); //Send the request
if (httpCode8 > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
timermode = payload.toInt();
Serial.print("Timer Mode=");
Serial.print(timermode); //Print the response payload
Serial.println();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
Serial.println("-------------------------------------------------------------------------------------");
http.end(); //Close connection
}
}
// alternatively use delay(500);
if ( TimePeriodIsOver(MyTestTimer, 500) ) {
ShowActualState();
}
switch (MyStateVariable) {
case CheckMode:
if (timermode == 0) {
MyStateVariable = CheckValue;
}
if (timermode == 1) {
MyStateVariable = OnOffTiming;
}
if (CheckCalibrationMode == 1) {
MyStateVariable = CalibrationModeON;
}
if (CheckCalibrationMode == 0) {
MyStateVariable = CalibrationModeOFF;
}
break;
case CalibrationModeON:
CalibrationModeON_TimeStamp = currentMillis;
Serial.println("Calibration Switch is ON");
MyStateVariable = CalibrationModeON_Wait;
break;
case CalibrationModeON_Wait:
if (currentMillis - CalibrationModeON_TimeStamp >= CalibrationModeON_Time) {
Serial.println("Sending Moisture Reading every 2 seconds");
int percentageHumididy = map(average, Cal_LowValueInWebsite, Cal_HighValueInWebsite, 0, 100);
Serial.print("Moisture Percentage = ");
Serial.print(percentageHumididy);
Serial.println("%");
Serial.print("Raw Sensor value = ");
Serial.println(average);
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
ESP.reset();
return;
}
String url = "/users/2106G001/GM/data/update.php?actual=" + String(percentageHumididy) + "&id=" + String(1);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
//delay(500);
while (client.available()) {
String line = client.readStringUntil('\r');
//Serial.print(line);
}
//digitalWrite(device1_pin,LOW);
MyStateVariable = CheckMode;
}
break;
case CalibrationModeOFF:
CalibrationModeOFF_TimeStamp = currentMillis;
Serial.println("Calibration Switch is OFF");
MyStateVariable = CalibrationModeOFF_Wait;
break;
case CalibrationModeOFF_Wait:
if (currentMillis - CalibrationModeOFF_TimeStamp >= CalibrationModeOFF_Time) {
Serial.println("Sending Moisture Reading every 1 minute");
int percentageHumididy = map(average, Cal_LowValueInWebsite, Cal_HighValueInWebsite, 0, 100);
Serial.print("Moisture Percentage = ");
Serial.print(percentageHumididy);
Serial.println("%");
Serial.print("Raw Sensor value = ");
Serial.println(average);
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
ESP.reset();
return;
}
String url = "/users/2106G001/GM/data/update.php?actual=" + String(percentageHumididy) + "&id=" + String(1);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
//delay(500);
while (client.available()) {
String line = client.readStringUntil('\r');
//Serial.print(line);
}
//digitalWrite(device1_pin,LOW);
MyStateVariable = CheckMode;
}
break;
case CheckValue:
if (SetValueInWebPage >= ActualSensorValueInWebPage) {
MyStateVariable = AutoModeSwitchOn;
}
if (SetValueInWebPage < ActualSensorValueInWebPage) {
MyStateVariable = CheckMode;
}
break;
case AutoModeSwitchOn:
digitalWrite(device1_pin, HIGH);
Serial.println("Actual Moisture Less Than Set Moisture. Switch Activated");
SwitchOnTimeStamp = currentMillis;
MyStateVariable = WaitForAutoModeOnTimeToEnd;
break;
case WaitForAutoModeOnTimeToEnd:
if (currentMillis - SwitchOnTimeStamp >= SwitchOnDurationInAutoMode) {
digitalWrite(device1_pin, LOW);
Serial.println("Switch Turned Off After Set Duration in AUTO mode");
MyStateVariable = SoakTimeStartOff;
}
break;
case SoakTimeStartOff:
SoakTimeStamp = currentMillis;
MyStateVariable = WaitForSoakTimeToEnd;
break;
case WaitForSoakTimeToEnd:
if (timermode == 1) {
MyStateVariable = OnOffTiming;
}
if (currentMillis - SoakTimeStamp >= SoakDurationInAutoMode) {
Serial.println("Soaking Time Over in AUTO mode");
MyStateVariable = CheckMode;
}
break;
case OnOffTiming:
digitalWrite(device1_pin, HIGH);
TimerModeOnTimeStamp = currentMillis;
Serial.println("Switch ON in TIMER mode");
MyStateVariable = WaitForTimerONTime_End;
break;
case WaitForTimerONTime_End:
if (timermode == 0) {
MyStateVariable = CheckValue;
}
if (currentMillis - TimerModeOnTimeStamp >= SwitchOnDurationInTimerMode) {
digitalWrite(device1_pin, LOW);
Serial.println("Switch Turned OFF in TIMER mode After Set Duration");
MyStateVariable = Timer_Start_OFF_Period;
}
break;
case Timer_Start_OFF_Period:
OFFPeriodStartsTimestamp = currentMillis;
MyStateVariable = WaitForTimerOFF_PeriodToEnd;
break;
case WaitForTimerOFF_PeriodToEnd:
if (timermode == 0) {
MyStateVariable = CheckValue;
}
if (currentMillis - OFFPeriodStartsTimestamp >= TimerPeriodSetInWebsite) {
digitalWrite(device1_pin, HIGH);
Serial.println("Switch ON in TIMER mode After Set Timer Period");
MyStateVariable = CheckMode;
}
break;
}
//delay (2000);
}
Below is from Serial Monitor
10:38:38.986 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:38.986 -> Sending Moisture Reading every 2 seconds
10:38:38.986 -> Moisture Percentage = 111%
10:38:38.986 -> Raw Sensor value = 1
10:38:39.173 -> Calibration Switch is ON
10:38:39.453 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:39.968 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:40.904 ->
10:38:41.326 -> Cal Low Value=5000
10:38:41.794 -> Cal High Value=500
10:38:42.168 -> Set Moisture=99
10:38:42.635 -> Actual Moisture=111
10:38:43.010 -> Set Timer=3600000
10:38:43.562 -> Set Duration=10000
10:38:44.120 -> Timer Mode=1
10:38:44.120 -> -------------------------------------------------------------------------------------
10:38:44.120 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:44.120 -> Sending Moisture Reading every 2 seconds
10:38:44.120 -> Moisture Percentage = 111%
10:38:44.120 -> Raw Sensor value = 1
10:38:44.354 -> Calibration Switch is ON
10:38:44.636 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:45.097 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:45.890 ->
10:38:46.309 -> Cal Low Value=5000
10:38:46.684 -> Cal High Value=500
10:38:47.102 -> Set Moisture=99
10:38:47.617 -> Actual Moisture=111
10:38:48.039 -> Set Timer=3600000
10:38:48.465 -> Set Duration=10000
10:38:48.882 -> Timer Mode=1
10:38:48.882 -> -------------------------------------------------------------------------------------
10:38:48.882 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:48.882 -> Sending Moisture Reading every 2 seconds
10:38:48.882 -> Moisture Percentage = 111%
10:38:48.882 -> Raw Sensor value = 1
10:38:49.069 -> Calibration Switch is ON
10:38:49.349 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:49.856 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:50.372 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:50.932 ->
10:38:51.447 -> Cal Low Value=5000
10:38:51.915 -> Cal High Value=500
10:38:52.335 -> Set Moisture=99
10:38:52.803 -> Actual Moisture=111
10:38:53.178 -> Set Timer=3600000
10:38:53.600 -> Set Duration=10000
10:38:54.067 -> Timer Mode=1
10:38:54.067 -> -------------------------------------------------------------------------------------
10:38:54.067 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:54.067 -> Sending Moisture Reading every 2 seconds
10:38:54.067 -> Moisture Percentage = 111%
10:38:54.114 -> Raw Sensor value = 1
10:38:54.301 -> Calibration Switch is ON
10:38:54.582 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:55.049 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:55.887 ->
10:38:56.400 -> Cal Low Value=5000
10:38:56.775 -> Cal High Value=500
10:38:57.191 -> Set Moisture=99
10:38:57.606 -> Actual Moisture=111
10:38:58.075 -> Set Timer=3600000
10:38:58.441 -> Set Duration=10000
10:38:58.958 -> Timer Mode=1
10:38:58.958 -> -------------------------------------------------------------------------------------
10:38:58.958 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:58.958 -> Sending Moisture Reading every 2 seconds
10:38:58.958 -> Moisture Percentage = 111%
10:38:58.958 -> Raw Sensor value = 1
10:38:59.145 -> Calibration Switch is ON
10:38:59.474 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:38:59.938 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:39:00.455 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:39:00.914 ->
10:39:01.424 -> Cal Low Value=5000
10:39:01.940 -> Cal High Value=500
10:39:02.438 -> Set Moisture=99
10:39:03.090 -> Actual Moisture=111
10:39:03.550 -> Set Timer=3600000
10:39:04.111 -> Set Duration=10000
10:39:04.667 -> Timer Mode=1
10:39:04.667 -> -------------------------------------------------------------------------------------
10:39:04.667 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:39:04.667 -> Sending Moisture Reading every 2 seconds
10:39:04.667 -> Moisture Percentage = 111%
10:39:04.667 -> Raw Sensor value = 1
10:39:04.854 -> Calibration Switch is ON
10:39:05.182 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:39:05.884 ->
10:39:06.302 -> Cal Low Value=5000
10:39:06.913 -> Cal High Value=500
10:39:07.521 -> Set Moisture=99
10:39:08.080 -> Actual Moisture=111
10:39:08.781 -> Set Timer=3600000
10:39:09.202 -> Set Duration=10000
10:39:09.669 -> Timer Mode=1
10:39:09.669 -> -------------------------------------------------------------------------------------
10:39:09.669 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:39:09.669 -> Sending Moisture Reading every 2 seconds
10:39:09.669 -> Moisture Percentage = 111%
10:39:09.669 -> Raw Sensor value = 0
10:39:09.903 -> Calibration Switch is ON
10:39:10.164 -> MyStateVariable is on value: CalibrationModeON_Wait (90)
10:39:10.912 ->
10:39:11.430 -> Cal Low Value=5000
10:39:11.850 -> Cal High Value=500
10:39:12.267 -> Set Moisture=99
10:39:12.689 -> Actual Moisture=111
10:39:13.206 -> Set Timer=3600000
10:39:13.722 -> Set Duration=10000
10:39:14.273 -> Timer Mode=1