I'm trying to simulate dynamic temperature using a small set of data with ESP32. I've just realized that the relay doesn't change the status if there is some variation of the temperature upper or lower the threshold.
If the temperature starts below the modeled temperature, the relay will turn on but, once it reaches the model's temperature or exceeds it, the status doesn't change, and the system will warm up till the next model.
Am I missing something in my code?
#include <OneWire.h>
#include <DallasTemperature.h>
#include <NTPClient.h>
#include <WiFi.h>
#include <WiFiUdp.h>
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 7200, 60000); //UTC+1 (Europe)
unsigned long current_time;
#define WIFI_AP "xxxxx"
#define WIFI_PASSWORD "xxxxx"
//WiFi SETUP
WiFiClient wifiClient;
int status = WL_IDLE_STATUS;
unsigned long lastSend;
const int oneWireBus1 = 0;
OneWire oneWire1 (oneWireBus1);
DallasTemperature sensors1 (&oneWire1);
const int relay1 = 02;
struct SetPoint {
unsigned long time;
float temperature;
};
#define DATA_SIZE 17
SetPoint scen1[DATA_SIZE] = {
{1622652330,26.97},//18h
{1622652390,25.62},
{1622678400,24.87},
{1622689200,24.16},
{1622700000,23.86},
{1622710800,25.17},
{1622721600,26.41},
{1622732400,27.22},
{1622743200,26.78},
{1622754000,25.83},
{1622764800,25.1},
{1622775600,24.6},
{1622786400,24.24},
{1622797200,26.81},
{1622808000,29.35},
{1622818800,29.38},
{1622829600,30.5}
};
unsigned int pos = 0;
void setup() {
Serial.begin(115200);
sensors1.begin();
pinMode(relay1, OUTPUT);
InitWiFi();
lastSend = 0;
timeClient.begin();
void loop() {
sensors1.requestTemperatures();
float temperature1 = sensors1.getTempCByIndex(0);
timeClient.update();
long current_time = timeClient.getEpochTime();
if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
if (temperature1 < scen1[pos].temperature) {
digitalWrite (relay1, HIGH);
}
else if (temperature1 > scen1[pos].temperature) {
digitalWrite (relay1, LOW);
}
pos++;
}
Serial.println(timeClient.getEpochTime());
Serial.println(timeClient.getFormattedTime());
Serial.println(pos);
Serial.println(scen1[pos].temperature);
Serial.println(scen1[pos-1].temperature);
Serial.print("Temperature Censius - Sensor 1: ");
Serial.print(temperature1);
Serial.println(" ÂșC ");
delay(3000);
}
(UPDATE)
Replacing the first if with while doesn't change anything.
The code works when taking if / else if out of nested if, but in this case I'm not able to increase time (the pos++ is also commented), and define limits according to the array size.
// if (pos < DATA_SIZE && current_time >= scen1[pos].time) {
if ((temperature1 < scen1[pos].temperature)&& (current_time >= scen1[pos].time)) {
digitalWrite (relay1, HIGH);
}
else if ((temperature1 > scen1[pos].temperature)&&(current_time >= scen1[pos].time)) {
digitalWrite (relay1, LOW);
}
// pos++;
// }