Time Controlled Switch using ESP32 Web Server and DS3231 RTC
Esp32 Time Based Controlling System
Table of Contents
Time Controlled Switch:
Time Controlled Switch using ESP32 Web Server and DS3231 RTC- With the help of this circuit and the Time Controlled ESP32 Web Server, now, you can convert any Switch or a relay into a Time Controlled Switch or a Time controlled relay. In fact you can convert any device into a time controlled device.
With this system, you can not only control small loads on time basis but you can also control large loads like, Water Pumps, Heaters, Refrigerators, Street lights, Generators, Door Locks, Blinds, in fact you can automatically turn ON or turn OFF any electrical load of your choice for a specific time duration. All you need is to set the Start Time and Stop Time and then leave everything else to the controller.
For this project, you will need an ESP32 WiFi + Bluetooth module, DS3231 RTC “Real-Time Clock”, and a 5V SPDT type relay.
Note: Weather Station Monitoring using ESP8266 and Webserver.
Amazon Links:
ESP32 WiFi+Bluetooth Module (Recommended)
*Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.
What is a DS3231 RTC?
The DS3231 is a highly accurate, low-power RTC module that provides precise timekeeping and calendar functions. It has built-in temperature compensation and a battery backup, ensuring accurate timekeeping even during power outages.
Pinout Description
The DS3231 module usually comes with six pins:
Pin | Description |
VCC | Power supply input (typically 3.3V to 5.5V) |
GND | Ground connection |
SDA | Serial Data Line for I2C communication |
SCL | Serial Clock Line for I2C communication |
SQW | Square Wave/Interrupt Output |
32K | 32KHz Output |
Key Specifications
Specification | Detail |
Voltage Supply | 3.3V to 5.5V |
Current Consumption | Less than 500μA |
Timekeeping Accuracy | ±2ppm at 0°C to +40°C |
Battery Backup Current | 3μA at 3V |
Temperature Range | -40°C to +85°C |
Memory | 236 bytes of battery-backed SRAM |
Interface | I²C Serial Interface (400kHz Max) |
Alarm Function | Dual programmable alarms |
Oscillator | Integrated TCXO |
Crystal |
32.768 kHz |
As usual, I am using my newly designed ESP32 Development board, because it already has most of the components needed for this project like for example a 5V relay, the ESP32 WiFi + Bluetooth module itself, and most importantly the 5V and 3A power supply. Since, this is a development board and I use it for making and testing my ESP32 based projects, so that’s why I have soldered female headers on the Left and Right sides of the ESP32 WiFi + Bluetooth module so that I can connect other sensors and breakout boards.
For this particular project, I have connected the DS3231 RTC “Real-Time Clock”. So, if you want to make the same Development board then you can watch my previous video available on my YouTube channel “Electronic Clinic” or you can read my previous article on the ESP32 Development board.
Anyway, you can also do the same exact connections on a breadboard. Let’s quickly go through all the connections.
Time Controlled Switch Circuit:
Connect the VCC and GND pins of the DS3231 to the ESP32 3.3V and GND. Connect the SDA and SCL pins of the DS3231 to the ESP32 GPIOs 21 and 22.
The 5V SPDT “Single Pole and Double throw” relay input is connected to the ESP32 GPIO 13.
There is no need to worry at all when you see this interface because you don’t have to design this page manually on your laptop or computer. All the code for this page is running on the ESP32 WiFi + Bluetooth module because we are using the ESP32 as a Web Server. Although this is a very basic interface, if you know the HTML coding, you can design yourself an amazing interface by modifying the code, I am about to share with you guys.
Anyways, this is the program of the ESP32 Web Server; you can modify this program according to your needs. I won’t go into too much detail because HTML coding is an entirely different field in itself. But, I am sure you would be able to make minor changes; once you read this code, you will get an idea.
Time Controlled Switch ESP32 Web Server Program:
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 |
#include <WiFi.h> #include <WebServer.h> #include <Wire.h> #include "RTClib.h" const char* ssid = "electroniclinic"; const char* password = "webserver"; RTC_DS3231 rtc; WebServer server(80); int setHour = -1, setMinute = -1, setSecond = -1; int stopHour = -1, stopMinute = -1, stopSecond = -1; bool loadControl = false; // To control the load const int loadPin = 13; // load connected to GPIO13 void handleRoot() { String html = "<!DOCTYPE html>" "<html>" "<head>" " <style>" " body {" " font-family: 'Arial', sans-serif;" " background-color: #f4f4f4;" " text-align: center;" " margin: 0;" " padding: 0;" " display: flex;" " flex-direction: column;" // Changed to column " justify-content: center;" " align-items: center;" " height: 100vh;" " }" " .clock,.set-timer, .stop-timer {" " background-color: #fff;" " padding: 25px;" " border-radius: 15px;" " box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);" " margin-bottom: 20px;" " }" " h1, h2 {" " font-size: 40px;" " color: #333;" " }" " .time, .date {" " font-size: 33px;" " color: #e87a05;" " margin: 20px 0;" " }" " .set-timer input, .set-timer button, .stop-timer input, .stop-timer button {" " font-size: 20px;" " color: #e87a05;" " margin: 20px 0;" " }" " .time span, .date span {" " font-weight: bold;" " }" " #setTime, #stopTime {" " font-weight: bold;" " font-size: 20px;" " }" " </style>" "</head>" "<body>" " <div class='clock'>" " <h1>Time Controlled Switch/Relay</h1>" " <h1>ESP32 Web Server</h1>" " <p class='time'>Time - <span id='_HOUR'>00</span>:<span id='_MIN'>00</span>:<span id='_SEC'>00</span></p>" " <p class='date'>Date - <span id='_DAY'>00</span>/<span id='_MONTH'>00</span>/<span id='_YEAR'>0000</span></p>" " </div>" " <div class='set-timer'>" " <h2>Set Start Time</h2>" " <input type='number' id='hour' placeholder='Hour' min='0' max='23'>" " <input type='number' id='minute' placeholder='Minute' min='0' max='59'>" " <input type='number' id='second' placeholder='Second' min='0' max='59'>" " <button onclick='setTime()'>Set Start Time</button>" " <p id='setTime'>Start Time: --:--:--</p>" " </div>" " <div class='stop-timer'>" // Add Stop Timer section " <h2>Set Stop Time</h2>" " <input type='number' id='stopHour' placeholder='Hour' min='0' max='23'>" " <input type='number' id='stopMinute' placeholder='Minute' min='0' max='59'>" " <input type='number' id='stopSecond' placeholder='Second' min='0' max='59'>" " <button onclick='stopTime()'>Set Stop Time</button>" " <p id='stopTime'>Stop Time: --:--:--</p>" " </div>" " <script>" " setInterval(function() {" " var xhttp = new XMLHttpRequest();" " xhttp.onreadystatechange = function() {" " if (this.readyState == 4 && this.status == 200) {" " const data = JSON.parse(this.responseText);" " document.getElementById('_HOUR').innerHTML = data.hour;" " document.getElementById('_MIN').innerHTML = data.minute;" " document.getElementById('_SEC').innerHTML = data.second;" " document.getElementById('_DAY').innerHTML = data.day;" " document.getElementById('_MONTH').innerHTML = data.month;" " document.getElementById('_YEAR').innerHTML = data.year;" " }" " };" " xhttp.open('GET', 'readwebRTC', true);" " xhttp.send();" " }, 1000);" " function setTime() {" " var hour = document.getElementById('hour').value;" " var minute = document.getElementById('minute').value;" " var second = document.getElementById('second').value;" " var xhttp = new XMLHttpRequest();" " xhttp.onreadystatechange = function() {" " if (this.readyState == 4 && this.status == 200) {" " document.getElementById('setTime').innerHTML = 'Set Time: ' + hour + ':' + minute + ':' + second;" " }" " };" " xhttp.open('GET', 'setTime?hour=' + hour + '&minute=' + minute + '&second=' + second, true);" " xhttp.send();" " }" " function stopTime() {" // Add JavaScript function for Stop Timer " var hour = document.getElementById('stopHour').value;" " var minute = document.getElementById('stopMinute').value;" " var second = document.getElementById('stopSecond').value;" " var xhttp = new XMLHttpRequest();" " xhttp.onreadystatechange = function() {" " if (this.readyState == 4 && this.status == 200) {" " document.getElementById('stopTime').innerHTML = 'Stop Time: ' + hour + ':' + minute + ':' + second;" " }" " };" " xhttp.open('GET', 'stopTime?hour=' + hour + '&minute=' + minute + '&second=' + second, true);" " xhttp.send();" " }" " </script>" "</body>" "</html>"; server.send(200, "text/html", html); } void handleRTCData() { DateTime now = rtc.now(); char json[128]; sprintf(json, "{\"hour\":%d, \"minute\":%d, \"second\":%d, \"day\":%d, \"month\":%d, \"year\":%d}", now.hour(), now.minute(), now.second(), now.day(), now.month(), now.year()); server.send(200, "application/json", json); } void handleSetTime() { setHour = server.arg("hour").toInt(); setMinute = server.arg("minute").toInt(); setSecond = server.arg("second").toInt(); loadControl = true; // Enable load control server.send(200, "text/plain", "Time Set"); } void handleStopTime() { stopHour = server.arg("hour").toInt(); stopMinute = server.arg("minute").toInt(); stopSecond = server.arg("second").toInt(); server.send(200, "text/plain", "Stop Time Set"); } void setup() { Serial.begin(115200); if (!rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } if (rtc.lostPower()) { Serial.println("RTC lost power, setting the time!"); rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected."); Serial.println("IP address: " + WiFi.localIP().toString()); server.on("/", handleRoot); server.on("/readwebRTC", handleRTCData); server.on("/setTime", handleSetTime); server.on("/stopTime", handleStopTime); pinMode(loadPin, OUTPUT); server.begin(); } void loop() { server.handleClient(); DateTime now = rtc.now(); if (loadControl && now.hour() == setHour && now.minute() == setMinute && now.second() == setSecond) { digitalWrite(loadPin, HIGH); // Turn on the LED } if (now.hour() == stopHour && now.minute() == stopMinute && now.second() == stopSecond) { digitalWrite(loadPin, LOW); // Turn off the LED loadControl = false; // Reset load control } } |
Anyway, If this is your first time using the ESP32 WiFi + Bluetooth module then you will also need to install the ESP32 board in the Arduino IDE. For this you can read my getting started article on the ESP32 WiFi + Bluetooth Module.
Next, you will also need to install the RTClib library. For this simply copy the library name then go to the Sketch Menu, then to Include Library, and click on the Manage Libraries.
Paste the library name in the search box.
You can see I have already installed this library.
Finally, you can upload this program; in my case I have already uploaded this program.
While the ESP32 is still connected to your Laptop or computer, open the Serial Monitor and Copy the IP Address. Then, you can disconnect the ESP32 WiFi + Bluetooth Module and get it installed near the Load you want to control.
Practical Demonstration:
For the practical demonstration, I am going to control a 110/220Vac bulb.
Safety:
Anyway, remember safety first, When the 110/220Vac supply is connected, never touch the relay contacts as it can be extremely dangerous. It is important to note that when working with mains voltage, proper safety precautions should always be taken and it is advisable to consult relevant electrical codes and standards.
Right now, the ESP32 WiFi + Bluetooth module, my Laptop, Tablet, and my cell phone all are connected to the WiFi router.
I can use any of these to wirelessly open the ESP32 Web Server. There is no need for these devices to be physically connected. Anyway, first let’s start with the Laptop.
All I need is to type or paste the IP Address. The interface will open in no-time.
To turn on a Load, first, set the Start Time and then set the Stop Time. This is the time that defines for how long the device will remain ON or Active.
As you can see, the Bulb just turned ON. Now, it will remain ON for exactly 1 minute.
Amazing, the bulb just turned OFF.
Next, I also used my Cell phone and tablet. For the practical demonstration, watch the video tutorial given below.
So, guy’s that’s all about the Time controlled Switch/Relay using ESP32 Web Server.
Watch Video Tutorial: