Task Automation based on Time using ESP32

Last Updated on April 9, 2025

Lets make Task Automation based on Time using ESP32 through NTP (Network Time Protocol), which requires Wi-Fi connectivity and it is more reliable than Internal RTC of ESP32 chip. By using NTP we can Synchronize ESP32 with time. We can schedule task when ever we want, like turning ON/OFF, reading sensor values or activate any actuators at a specific time without needing a real time clock (RTC) module. It will use accurate internet time and it is more efficient than external RTCs like DS3231 or DS1307.




Here ESP32 with the NTPClient library, fetch real time from the internet and use it to control a Relay module based on the Task Time Schedule. For this project we need Wi-Fi with internet access.

How the NTP Works?

NTP (Network Time Protocol) used to synchronize the clocks of IoT devices, Computers and other devices on a network (Internet). NTP fetches the current time from internet servers (NTP Servers), It allows device to maintain accurate time keeping by synchronizing their clocks with the reference time source like pool-ntp.org, we will use the NTPClient library to handle this.

Know more about Reading NTP client server to get current Date and Time with ESP32.

List of Requirements

Before starting to code ESP32 for Task Automation check these list of requirements.

  • Hope you have Arduino IDE, if not download and install it from arduino.cc
  • If you are new to code ESP32 board using Arduino IDE, then you have to add the following url to the “Additional Boards Manager URLs
    • https://raw.githubusercontent.com/espressif/arduino-esp32/master/package_esp32_index.json
  • Then go to Tools>Boards>Board managers then search “ESP32” and install the package by Espressif.
  • If you want more details read here to get started with ESP32 Arduino IDE
  • Then select board in Arduino IDE under Tools>Board, choose DOIT ESP32 DEVKIT V1 or (your Specific board name)
  • Then check & Install the following libraries.
    • Open Sketch>Include Library>Manage Libraries
    • WiFi (Mostly pre installed in ESP32 board Package, See here)
    • NTPClient by Fabrice Weinberg (This is for time Synchronization from Internet)

Simple Task Automation Circuit Diagram

Working Video

Construction & Working

To demonstrate Task Automation based on Real time using ESP32 micro controller, we used 5V SPDT Relay and RGB LED, Here the ESP32 GPIO output voltage is 3.3V and so we used transistor Logic Level shifter to drive 5V relay. Red terminal of RGB LED is connected to the Normally Close (N/C) and Green terminal of RGB LED is connected to the Normally Open (N/O) of relay.

When ever the mentioned time comes then the GPIO pin (2) will be set HIGH and makes Green LED glow through Relay for particular duration that we mention in code (This is Task – It can be customized depends on your need). Remaining time GPIO Pin (2) in LOW, Red LED will glow and wait for specific time to change task that is output.

Code

We know Some countries following DST (Day Light Saving Time) and some countries don’t. Here we have made two different code with and without DST, use those codes depends on you need.

Considering UAE (change depends on your living country). You have to calculate the total offset in seconds. For the UAE time zone (GMT+4) to put it on code.

  • 4 Hours X 60 Minutes/hour X 60 Seconds/minute
    • 4*60*60 = 14400
    • NTPClient(ntpUDP, “pool.ntp.org”, timeOffsetInSeconds, updateInterval)
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>

// Wi-Fi credentials
const char* ssid = "Your SSID";
const char* password = "Your Wi-Fi Password";


// Relay pin
const int relayPin = 2;

// Scheduled ON/OFF times
int onHour = 19;   // 7:45 PM
int onMinute = 45;

int offHour = 19;  // 7:47 PM
int offMinute = 47;
 
WiFiUDP ntpUDP;

// Time offset in seconds for your timezone
// Example: 14400 = United Arab Emirates Standard Time (UTC +4:00)
NTPClient timeClient(ntpUDP, "pool.ntp.org", 14400, 60000); 

void setup() {
  Serial.begin(115200);

  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW); // Relay OFF initially

  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");

  timeClient.begin();
}

void loop() {
  timeClient.update();

  // Get current time details
  int currentHour = timeClient.getHours();
  int currentMinute = timeClient.getMinutes();
  int currentSecond = timeClient.getSeconds();

  // Print formatted time
  Serial.printf("Current Time: %02d:%02d:%02d\n", currentHour, currentMinute, currentSecond);

  // Print current date (derived from UNIX timestamp)
  unsigned long epochTime = timeClient.getEpochTime();
  struct tm *ptm = gmtime((time_t *)&epochTime);

  int day = ptm->tm_mday;
  int month = ptm->tm_mon + 1;  // Months since January (0-11)
  int year = ptm->tm_year + 1900;

  Serial.printf("Current Date: %02d-%02d-%d\n", day, month, year);

  // Control relay
  if (currentHour == onHour && currentMinute == onMinute) {
    digitalWrite(relayPin, HIGH);
    Serial.println("Relay ON");
  }

  if (currentHour == offHour && currentMinute == offMinute) {
    digitalWrite(relayPin, LOW);
    Serial.println("Relay OFF");
  }

  delay(10000); // Check every 10 Seconds
}

Code With DST (Task Automation)

Here is the example code for countries following DST, code for London (England)

#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <time.h>

// Wi-Fi credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

// Relay pin
const int relayPin = 2;9

// Scheduled ON/OFF times (24h format, in local time)
int onHour = 18;   // 6:00 PM
int onMinute = 30;
int offHour = 22;  // 10:00 PM
int offMinute = 0;

WiFiUDP ntpUDP;
// Initial timezone offset (will be updated based on DST)
int timeOffset = 0;
NTPClient timeClient(ntpUDP, "pool.ntp.org", timeOffset, 60000);

// Function to calculate the last Sunday of a given month
int lastSunday(int year, int month) {
  struct tm timeinfo = {0};
  timeinfo.tm_year = year - 1900;
  timeinfo.tm_mon = month;
  timeinfo.tm_mday = 31; // Start from end of month
  mktime(&timeinfo); // Normalize to find the correct weekday
  int wday = timeinfo.tm_wday;
  return 31 - wday;
}

// Function to check whether current date is in DST range (UK)
bool isDST(struct tm* timeinfo) {
  int year = timeinfo->tm_year + 1900;
  int month = timeinfo->tm_mon;
  int day = timeinfo->tm_mday;

  if (month < 2 || month > 9) return false;     // Jan-Feb & Nov-Dec: no DST
  if (month > 2 && month < 9) return true;      // Apr-Sep: DST

  int lastMarchSunday = lastSunday(year, 2);    // March
  int lastOctSunday = lastSunday(year, 9);      // October

  if (month == 2) return (day >= lastMarchSunday);
  if (month == 9) return (day < lastOctSunday);

  return false;
}

void setup() {
  Serial.begin(115200);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);

  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");

  timeClient.begin();
}

void loop() {
  timeClient.update();
  unsigned long epochTime = timeClient.getEpochTime();

  struct tm *timeinfo = gmtime((time_t*)&epochTime);

  // Update DST status
  bool dst = isDST(timeinfo);
  int currentOffset = dst ? 3600 : 0;
  timeClient.setTimeOffset(currentOffset);  // Update offset if DST status changes

  int hour = (timeinfo->tm_hour + (dst ? 1 : 0)) % 24; // Adjust hour
  int minute = timeinfo->tm_min;
  int second = timeinfo->tm_sec;
  int day = timeinfo->tm_mday;
  int month = timeinfo->tm_mon + 1;
  int year = timeinfo->tm_year + 1900;

  Serial.printf("Current Time: %02d:%02d:%02d (%s)\n", hour, minute, second, dst ? "BST" : "GMT");
  Serial.printf("Current Date: %02d-%02d-%d\n", day, month, year);

  // Relay control
  if (hour == onHour && minute == onMinute) {
    digitalWrite(relayPin, HIGH);
    Serial.println("Relay ON");
  }
  if (hour == offHour && minute == offMinute) {
    digitalWrite(relayPin, LOW);
    Serial.println("Relay OFF");
  }

  delay(60000); // check once per minute
}
Hope this article helps you to build, Time based task automation project. You can enhance this code to make multiple task in different time, or using sensor to read sensed value at particular time. If you have any questions let us know through comments.




Leave a Reply

Your email address will not be published. Required fields are marked *