hello i am receiving the following prints after uploading my code into my ESP 32 DEV module.
when uploading different sketch's it worked fine.
this is the error :
rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0030,len:4832
load:0x40078000,len:16460
load:0x40080400,len:4
load:0x40080404,len:3504
entry 0x400805cc
this is the code: `#include <WiFi.h>
#include <WebServer.h>
#include <time.h> // Time library for handling time and date
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>
#define ONE_WIRE_BUS 7 // Pin connected to the DS18B20
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to DallasTemperature
DallasTemperature sensors(&oneWire);
typedef String (*PinStatusFunction)(); // Define a function pointer type
const char* ssid = "yosi"; // Replace with your Wi-Fi SSID
const char* password = "sara0112"; // Replace with your Wi-Fi password
WebServer server(80);
const int Frezzer_relay = 12; // GPIO pin where LED is connected
const int filteringPin = 13;
const int fillingPin = 14;
const int emptyingPin = 15;
unsigned long lastTempControlTime[10]; // Store last execution time for TempControl
const unsigned long tempControlInterval = 2000; // Interval in milliseconds (2 seconds)
const long gmtOffset_sec = 3600 * 3; // GMT+3 for Israel (summer time)
const int daylightOffset_sec = 0; // 0 for Israel in summer (or +3600 if considering daylight saving)
struct AlramSetup {
int id;//unique id for each alarm
int Arr_DaysOfTheWeek[7]; // Days of the week
bool Recurring; // Is the alarm recurring?
bool Filtering; // Should filtering be activated?
bool Cooling; // Should cooling be activated?
bool Fill_Tank; // Should the tank be filled?
bool Empty_Tank; // Should the tank be emptied?
time_t time; // Time for the alarm (HH:MM)
// For TempControl
unsigned long lastTempControlTime; // Last execution time of TempControl
bool tempControlActive; // Is TempControl currently active?
};
int alarmCount=0;
// Global variables for the system
unsigned long relayStartTime; // Shared start time for the active relay
bool relayActive = false; // Shared active state for any relay
AlramSetup alarms[10];
String getCoolingPinStatus() {
if (digitalRead(Frezzer_relay) == HIGH) {
return "ON"; // Cooling relay is ON
} else {
return "OFF"; // Cooling relay is OFF
}
}
String getfilteringPinStatus() {
if (digitalRead(filteringPin) == HIGH) {
return "ON"; // Cooling relay is ON
} else {
return "OFF"; // Cooling relay is OFF
}
}
String getfillingPinStatus() {
if (digitalRead(fillingPin) == HIGH) {
return "ON"; // Cooling relay is ON
} else {
return "OFF"; // Cooling relay is OFF
}
}
String getemptyingPinStatus() {
if (digitalRead(emptyingPin) == HIGH) {
return "ON"; // Cooling relay is ON
} else {
return "OFF"; // Cooling relay is OFF
}
}
// Function to sync time with NTP server
void syncTime() {
configTime(gmtOffset_sec, daylightOffset_sec, "pool.ntp.org", "time.nist.gov");
Serial.print("Waiting for time");
while (!time(nullptr)) {
Serial.print(".");
delay(1000);
}
Serial.println("\nTime synchronized!");
}
void TempControl()
{
sensors.requestTemperatures(); // Request temperature readings
float temperature = sensors.getTempCByIndex(0); // Read temperature in Celsius
if (temperature == -127.00) {
Serial.println("Failed to read from DS18B20 sensor!");
} else {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
}
if(temperature<3)
{
digitalWrite(Frezzer_relay,LOW);
}
if(temperature>=4)
{
digitalWrite(Frezzer_relay,HIGH);
}
}
void handleTempControl(AlramSetup &alarm) {
// Check if TempControl is active and within the 50-minute duration
if (relayActive && (millis() - relayStartTime < 3000000)) {
// Call TempControl() periodically
if (millis() - alarm.lastTempControlTime >= tempControlInterval) { // Enter every two seconds
TempControl(); // Call the temperature control function
alarm.lastTempControlTime = millis(); // Update last execution time
}
}
}
void RelayOnLogic(int pin, String nameToPrint) {
digitalWrite(pin, HIGH); // Turn on the specified relay
relayStartTime = millis(); // Record the start time
relayActive = true; // Mark the relay as active
Serial.print(nameToPrint); // Print the relay name
Serial.println(" relay turned on");
}
void RelayOFFLogic(int pin, String nameToPrint) {
digitalWrite(pin, LOW); // Turn on the specified relay
relayActive = false; // Mark the relay as active
relayStartTime=0;
Serial.print(nameToPrint); // Print the relay name
Serial.println(" relay turned off");
}
void checkAlarms() {
time_t now = time(nullptr); // Get current time in seconds since epoch
struct tm* currentTime = localtime(&now);
int currentDay = currentTime->tm_wday; // 0 = Sunday, 6 = Saturday
for (int i = 0; i < alarmCount; i++) {
// Check if the alarm is scheduled for today and matches the current time
if (alarms[i].Arr_DaysOfTheWeek[currentDay] == 1 && difftime(now, alarms[i].time-40*60) >= 0) {
// Cooling relay
if (alarms[i].Cooling) {
handleTempControl(alarms[i]);
}
// Filtering relay
if (alarms[i].Filtering) {
RelayOnLogic(Frezzer_relay,"Filtering");
}
// Filling tank relay
if (alarms[i].Fill_Tank) {
RelayOnLogic(fillingPin,"Filling");
}
// Emptying tank relay
if (alarms[i].Empty_Tank) {
RelayOnLogic(emptyingPin,"Emptying");
}
// Emptying tank relay
}
if (relayActive && (millis() - relayStartTime >= 3000000)) {
if (alarms[i].Cooling) {
RelayOFFLogic(Frezzer_relay,"Frezzer");
} else if (alarms[i].Filtering) {
RelayOFFLogic(filteringPin,"Filtering");
} else if (alarms[i].Fill_Tank) {
RelayOFFLogic(fillingPin,"Filling");
} else if (alarms[i].Empty_Tank) {
RelayOFFLogic(emptyingPin,"Emptying");
}
}
}
}
void handleRelayStatus(PinStatusFunction pin, String relay_name) {
String status = pin(); // Call the function passed in to get the status
String jsonResponse = "{\"" + relay_name + "\": \"" + status + "\"}"; // Use relay_name for the key in JSON
server.send(200, "application/json", jsonResponse); // Send the status in JSON format
}
void deleteAlarm(int alarmId) {
if (alarmCount == 1) {
if (alarms[0].id == alarmId) { // Ensure the ID matches
alarms[0] = {}; // Clear the alarm
alarmCount--; // Decrement the count
Serial.print("Alarm with ID ");
Serial.print(alarmId);
Serial.println(" deleted successfully.");
} else {
Serial.print("No alarm found with ID ");
Serial.println(alarmId);
}
return;
}
for (int i = 0; i < alarmCount; i++) {
if (alarms[i].id == alarmId) {
// Shift all alarms down to fill the gap
for (int j = i; j < alarmCount - 1; j++) {
alarms[j] = alarms[j + 1];
}
// Optionally reset the last alarm
alarms[alarmCount - 1] = {}; // Clear the last alarm after shift
alarmCount--; // Decrease the count of alarms
Serial.print("Alarm with ID ");
Serial.print(alarmId);
Serial.println(" deleted successfully.");
return;
}
}
Serial.print("No alarm found with ID ");
Serial.println(alarmId);
}
void PinSetup()
{
pinMode(Frezzer_relay,OUTPUT);
pinMode(filteringPin,OUTPUT);
pinMode(fillingPin,OUTPUT);
pinMode(emptyingPin,OUTPUT);
digitalWrite(Frezzer_relay,LOW);
digitalWrite(filteringPin,LOW);
digitalWrite(fillingPin,LOW);
digitalWrite(emptyingPin,LOW);
}
void WifiSetup()
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println(WiFi.localIP());
}
void deleteAlarmSetup()
{
server.on("/deleteAlarm", HTTP_POST, []() {
if (server.hasArg("id")) {
int alarmId = server.arg("id").toInt();
deleteAlarm(alarmId);
server.send(200, "text/plain", "Alarm deleted.");
} else {
server.send(400, "text/plain", "No ID provided.");
}
});
}
void handleRelayStatusSetup()
{
handleRelayStatus(getCoolingPinStatus, "coolingRelay");
handleRelayStatus(getfilteringPinStatus, "filteringPin");
handleRelayStatus(getfillingPinStatus, "fillingPin");
handleRelayStatus(getemptyingPinStatus, "emptyingPin");
}
void setAlarmSetup() {
server.on("/setAlarm", HTTP_POST, []() {
if (server.hasArg("plain")) { // Check if the request contains a body (JSON)
String body = server.arg("plain"); // Get the body of the request
parseAlarm(body); // Pass the body to parseAlarm function
server.send(200, "text/plain", "Alarm set successfully.");
} else {
server.send(400, "text/plain", "Invalid request. No JSON body found.");
}
});
}
void handleAlarms() {
DynamicJsonDocument doc(1024);
JsonArray alarmsArray = doc.to<JsonArray>();
// Convert each alarm struct into a JSON object
for (int i = 0; i < alarmCount; i++) {
JsonObject alarmJson = alarmsArray.createNestedObject();
alarmJson["id"] = alarms[i].id;
// Create a JsonArray for the daysOfWeek
JsonArray daysOfWeekJson = alarmJson.createNestedArray("daysOfWeek");
for (int j = 0; j < 7; j++) {
daysOfWeekJson.add(alarms[i].Arr_DaysOfTheWeek[j]); // Add each day to the JSON array
}
alarmJson["recurring"] = alarms[i].Recurring;
alarmJson["filtering"] = alarms[i].Filtering;
alarmJson["cooling"] = alarms[i].Cooling;
alarmJson["fillTank"] = alarms[i].Fill_Tank;
alarmJson["emptyTank"] = alarms[i].Empty_Tank;
alarmJson["time"] = alarms[i].time;
}
String response;
serializeJson(doc, response);
// Send the JSON response
server.send(200, "application/json", response);
}
void temperature()
{
sensors.requestTemperatures(); // Request temperature readings
float temperature = sensors.getTempCByIndex(0); // Read temperature in Celsius
server.send(200, "text/plain", String(temperature));
}
void setup() {
Serial.begin(115200);
PinSetup();
sensors.begin();
WifiSetup();
syncTime();
deleteAlarmSetup();
handleRelayStatusSetup();
setAlarmSetup();
server.on("/alarms", HTTP_GET, handleAlarms);
server.on("/temperature", HTTP_GET, temperature);
server.begin();
}
void parseAlarm(String body) {
StaticJsonDocument<512> doc;
// Check for deserialization errors
DeserializationError error = deserializeJson(doc, body);
if (error) {
Serial.print(F("Failed to parse JSON: "));
Serial.println(error.c_str());
return;
}
if (alarmCount < 10) { // Limit to 10 alarms
AlramSetup newAlarm;
// Check if the daysOfWeek field exists and has exactly 7 elements
if (!doc.containsKey("daysOfWeek")) {
Serial.println(F("Missing 'daysOfWeek' field in JSON."));
return;
}
JsonArray days = doc["daysOfWeek"];
if (days.size() != 7) {
Serial.println(F("'daysOfWeek' array must have exactly 7 elements."));
return;
}
// Copy the days of the week to the alarm setup
for (int i = 0; i < 7; i++) {
newAlarm.Arr_DaysOfTheWeek[i] = days[i];
}
// Parse and validate other fields
newAlarm.id = doc["id"];
newAlarm.Recurring = doc["recurring"];
newAlarm.Filtering = doc["filtering"];
newAlarm.Cooling = doc["cooling"];
newAlarm.Fill_Tank = doc["fillTank"];
newAlarm.Empty_Tank = doc["emptyTank"];
// Parse the time string (e.g., "12:00") and convert to `time_t`
if (!doc.containsKey("time")) {
Serial.println(F("Missing 'time' field in JSON."));
return;
}
String timeString = doc["time"];
struct tm tm;
// Parse the time string assuming it's in "HH:MM" format
if (strptime(timeString.c_str(), "%H:%M", &tm) == NULL) {
Serial.println(F("Invalid time format. Expected 'HH:MM'."));
return;
}
time_t now = time(nullptr);
struct tm* now_tm = localtime(&now);
// Set the current year, month, and day
tm.tm_year = now_tm->tm_year;
tm.tm_mon = now_tm->tm_mon;
tm.tm_mday = now_tm->tm_mday;
// Convert to time_t
newAlarm.time = mktime(&tm);
// Check if the new alarm is at least 50 minutes apart from existing alarms on the same day
const time_t MIN_TIME_DIFF = 50 * 60; // 50 minutes in seconds
for (int i = 0; i < alarmCount; i++) {
for (int day = 0; day < 7; day++) {
if (newAlarm.Arr_DaysOfTheWeek[day] == 1 && alarms[i].Arr_DaysOfTheWeek[day] == 1) {
// Both alarms are scheduled for the same day, check the time difference
if (abs(difftime(newAlarm.time, alarms[i].time)) < MIN_TIME_DIFF) {
Serial.println(F("Error: Alarm time is less than 50 minutes apart from an existing alarm on the same day."));
return;
}
}
}
}
// Add the new alarm to the array
alarms[alarmCount] = newAlarm;
alarmCount++;
Serial.println(F("Alarm set successfully!"));
} else {
Serial.println(F("Alarm limit reached!"));
}
}
void loop() {
server.handleClient();
checkAlarms();
}
`