NTPClient not returning current time when esp32 host server on static ip

Guys i am currently working on project which requires to host esp32 on static ip and it needs to perform task when set time is reached to get time i am using ntpclient "pool.ntp.org" but it dose not return correct time

#include <Wire.h>
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char* ssid = "ssid";
const char* password = "password";

IPAddress staticIP(192, 168, x, x);
IPAddress gateway(192, 168, x, x);
IPAddress subnet(255, 255, x, x);

AsyncWebServer server(80);

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP,"pool.ntp.org");

int t1start;
int t2start;
int t3start;
int t4start;
int t1duration = 2; // 10s
int t2duration = 10;
int t3duration = 10; // 10s
int receivedHour;
int receivedMinute;

bool executed1 = false;
bool executed2 = false;
bool executed3 = false;
bool executed4 = false;
bool executed5 = false;

void setup() {
  Serial.begin(115200);
  delay(3000);
  WiFi.config(staticIP, gateway, subnet, subnet);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println(WiFi.localIP());

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", "Hello from ESP32!");
  });

  server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", "Hello from index.html!");
  });

  server.on("/time", HTTP_GET, [](AsyncWebServerRequest *request) {
    if (request->hasParam("hour") && request->hasParam("minute")) {
      String hour = request->getParam("hour")->value();
      String minute = request->getParam("minute")->value();

      // Convert hour and minute to integers if needed
      receivedHour = hour.toInt();
      receivedMinute = minute.toInt();

      // Process received hour and minute here
      Serial.print("Received Hour: ");
      Serial.println(receivedHour);
      Serial.print("Received Minute: ");
      Serial.println(receivedMinute);

      request->send(200, "text/plain", "Time received successfully");
    } else {
      request->send(400, "text/plain", "Invalid request");
    }
  });

  DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
  server.begin();

  timeClient.begin();
  timeClient.setTimeOffset(19800); // Indian Standard Time (GMT +5:30)
}

int convert(int hour, int min, int sec)
{
  return hour * 3600 + min * 60 + sec; // Calculate total seconds
}

void loop() {
  timeClient.update();
  delay(200);
  int currentHour = timeClient.getHours();
  int currentMinute = timeClient.getMinutes();
  int currentSecond = timeClient.getSeconds();
  
  Serial.print(currentHour); // Print current hour
  Serial.print(":"); // Separator
  Serial.println(currentMinute); // Print current minute

  int currentTime = convert(currentHour, currentMinute, currentSecond);
  Serial.println(currentTime); // Print current time in seconds

  if (currentHour == receivedHour && currentMinute == receivedMinute && currentMinute <= 5 && !executed1) {
    startT1();
    startR1();
    t1start = currentTime;
    executed1 = true;
  }

  if ((currentTime - t1start >= t1duration) && executed1 && !executed2) {
    stopT1();
    stopR1();
    startT2();
    t2start = currentTime;
    executed2 = true;
  }
  
}

I raised similar topic for esp8266 here is the link for that topic

and here I just can give a similar answer:

remove the external NTP library.

NTP on the ESP comes with the ESP Core - no need for an external NTP library.

See my page:
https://werner.rothschopf.net/microcontroller/202103_arduino_esp32_ntp_en.htm

hare is the updated code according to your doc but it is still not working am i doing something wrong

#ifndef STASSID
#define STASSID "ssid"          // set your SSID
#define STAPSK "pass"       // set your wifi password
#endif

/* Configuration of NTP */
// choose the best fitting NTP server pool for your country
#define MY_NTP_SERVER "in.pool.ntp.org"

// choose your time zone from this list
// https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
#define MY_TZ "IST-5:30"

/* Necessary Includes */
#ifdef ARDUINO_ARCH_ESP32
#include <WiFi.h>                     // we need wifi to get internet access
#endif
#ifdef ARDUINO_ARCH_ESP8266
#include <ESP8266WiFi.h> 
#endif
#include <time.h>   
#include <Wire.h>     
#include <WiFiUdp.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>            // for time() ctime()

/* Globals */
time_t now;                          // this are the seconds since Epoch (1970) - UTC
tm tm;                             // the structure tm holds time information in a more convenient way *

IPAddress staticIP(192, 168, x, x);
IPAddress gateway(192, 168, x, x);
IPAddress subnet(255, 255, x, x);

AsyncWebServer server(80);


int t1start;
int t2start;
int t3start;
int t4start;
int t1duration = 2; // 10s
int t2duration = 10;
int t3duration = 10; // 10s
int receivedHour;
int receivedMinute;

bool executed1 = false;
bool executed2 = false;
bool executed3 = false;
bool executed4 = false;
bool executed5 = false;


void setup() {
  Serial.begin(115200);
  Serial.println("\nNTP TZ DST - bare minimum");

  #ifdef ARDUINO_ARCH_ESP32
  // ESP32 seems to be a little more complex:
  configTime(0, 0, MY_NTP_SERVER);  // 0, 0 because we will use TZ in the next line
  setenv("TZ", MY_TZ, 1);            // Set environment variable with your time zone
  tzset();
  #else
  // ESP8266
  configTime(MY_TZ, MY_NTP_SERVER);    // --> for the ESP8266 only
  #endif

  // start network
  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);
  WiFi.config(staticIP, gateway, subnet, subnet);
  WiFi.begin(STASSID, STAPSK);
  while (WiFi.status() != WL_CONNECTED) {
    delay(200);
    Serial.print ( "." );
  }
  Serial.println("\nWiFi connected");
  Serial.println(WiFi.localIP());

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", "Hello from ESP32!");
  });

  server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", "Hello from index.html!");
  });

  server.on("/time", HTTP_GET, [](AsyncWebServerRequest *request) {
    if (request->hasParam("hour") && request->hasParam("minute")) {
      String hour = request->getParam("hour")->value();
      String minute = request->getParam("minute")->value();

      // Convert hour and minute to integers if needed
      receivedHour = hour.toInt();
      receivedMinute = minute.toInt();

      // Process received hour and minute here
      Serial.print("Received Hour: ");
      Serial.println(receivedHour);
      Serial.print("Received Minute: ");
      Serial.println(receivedMinute);

      request->send(200, "text/plain", "Time received successfully");
    } else {
      request->send(400, "text/plain", "Invalid request");
    }
  });

  DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
  server.begin();
}

int convert(int hour, int min, int sec)
{
  return hour * 3600 + min * 60 + sec; // Calculate total seconds
}

void loop() {
  time(&now); // read the current time
  localtime_r(&now, &tm);             // update the structure tm with the current time
  Serial.print("\thour:");
  Serial.print(tm.tm_hour);           // hours since midnight 0-23
  Serial.print("\tmin:");
  Serial.print(tm.tm_min);            // minutes after the hour 0-59
  Serial.print("\tsec:");
  Serial.print(tm.tm_sec);
  if (tm.tm_isdst == 1)               // Daylight Saving Time flag
    Serial.print("\tDST");  
  else
    Serial.print("\tstandard");
  Serial.println();
  int currentHour = tm.tm_hour;
  int currentMinute =tm.tm_min;
  int currentSecond = tm.tm_sec;
  int currentTime = convert(currentHour, currentMinute, currentSecond);

  if (currentHour == receivedHour && currentMinute == receivedMinute && currentMinute <= 5 && !executed1) {
    startT1();
    startR1();
    t1start = convert(currentHour, currentMinute, currentSecond);
    executed1 = true;
  }

  if ((currentTime - t1start >= t1duration) && executed1 && !executed2) {
    stopT1();
    stopR1();
    startT2();
    t2start = convert(currentHour, currentMinute, currentSecond);
    executed2 = true;
  }

  if ((currentTime - t2start >= t2duration) && executed1 && executed2 && !executed3) {
    stopT2();
    startR2();
    startT3();
    t3start = convert(currentHour, currentMinute, currentSecond);
    executed3 = true;
  }

  if ((currentTime - t3start >= t3duration) && executed1 && executed2 && executed3 && !executed4) {
    stopT3();
    stopR2();
    t4start = convert(currentHour, currentMinute, currentSecond);
    executed4 = true;
  }

  delay(1000); // dirty delay
}


void startR1() {
  Serial.println("R1 start");
}

void startT1() {
  Serial.println("T1 start");
}

void stopR1() {
  Serial.println("R1 stop");
}

void stopT1() {
  Serial.println("T1 stop");
}

void startR2() {
  Serial.println("R2 start");
}

void startT2() {
  Serial.println("T2 start");
}

void stopR2() {
  Serial.println("R2 stop");
}

void stopT2() {
  Serial.println("T2 stop");
}

void startT3() {
  Serial.println("T3 start");
}

void stopT3() {
  Serial.println("T3 stop");
}

last time it was a wifi config problem related to this line of code
WiFi.config(staticIP, gateway, subnet, subnet);

last time I showed you already how to make that line correct.

WiFi.config(ip, dns, gateway, subnet);

Why do you want to hand over the subnet two times?
set the dns and the gateway to your routers ip and it will work.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.