Skip to content

Instantly share code, notes, and snippets.

@tranchausky
Created August 20, 2024 16:39
Show Gist options
  • Save tranchausky/3ba3a634b2077dd54ca75569ecfb0191 to your computer and use it in GitHub Desktop.
Save tranchausky/3ba3a634b2077dd54ca75569ecfb0191 to your computer and use it in GitHub Desktop.
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <TimeLib.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// NTP Server settings
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 3600; // GMT offset in seconds
const int daylightOffset_sec = 3600; // Daylight offset in seconds
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, ntpServer, gmtOffset_sec, 60000); // Update interval: 60s
bool isTimeInRange(int fromHour, int toHour) {
int currentHour = hour(); // Get the current hour from TimeLib
// Ensure 'fromHour' and 'toHour' are within 24-hour format
fromHour = fromHour % 24;
toHour = toHour % 24;
// Handle cases where the range spans midnight
if (fromHour <= toHour) {
return (currentHour >= fromHour && currentHour <= toHour);
} else {
return (currentHour >= fromHour || currentHour <= toHour);
}
}
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
// Initialize NTP Client
timeClient.begin();
timeClient.update();
// Set up the time (NTP client updates this automatically)
setTime(timeClient.getEpochTime());
int fromHour = 10; // 10 AM
int toHour = 14; // 2 PM
if (isTimeInRange(fromHour, toHour)) {
Serial.println("The current time is within the range.");
} else {
Serial.println("The current time is outside the range.");
}
}
void loop() {
timeClient.update(); // Update time from NTP server
setTime(timeClient.getEpochTime()); // Set the time
// Your main code here
delay(10000); // Wait 10 seconds before the next update
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment