Cannot connect to NTP server with fixed IP
Posted: Mon May 13, 2019 1:31 pm
Hi
I usually use the sketch from here https://lastminuteengineers.com/esp32-n ... -tutorial/ to get the time via NTP. But when I use a fixed IP for my ESP32, the connexion to the NTP server doesn't work anymore.
Here is the modified sketch: the fixed IP part works in any other conditions.
I get :
I usually use the sketch from here https://lastminuteengineers.com/esp32-n ... -tutorial/ to get the time via NTP. But when I use a fixed IP for my ESP32, the connexion to the NTP server doesn't work anymore.
Here is the modified sketch: the fixed IP part works in any other conditions.
Code: Select all
#include <WiFi.h>
#include "time.h"
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASS";
// **** These lines added :
//Static IP address configuration
IPAddress staticIP(192, 168, 0, 51); //ESP32 static ip
IPAddress gateway(192, 168, 0, 254); //IP Address of WiFi Router
IPAddress subnet(255, 255, 255, 0); //Subnet mask
IPAddress dns(192, 168, 0, 254); //DNS
// *** up to here
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 3600;
const int daylightOffset_sec = 3600;
void printLocalTime()
{
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}
void setup()
{
Serial.begin(115200);
//connect to WiFi
Serial.printf("Connecting to %s ", ssid);
// **** These lines added :
WiFi.mode(WIFI_OFF);
WiFi.config(staticIP, dns, gateway, subnet);
WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only)
delay(100);
// *** up to here
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
Serial.print("WiFi connected - IP address: ");
Serial.println(WiFi.localIP());
//init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void loop()
{
delay(1000);
printLocalTime();
}
What is wrong? Thanks for your help.Connecting to ***.. CONNECTED
WiFi connected - IP address: 192.168.0.51
Failed to obtain time