Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- #include <ESP8266HTTPClient.h>
- #include <ESP8266WiFi.h>
- #include <string>
- const char *SSID = "SSID";
- const char *WiFiPass = "pwkey";
- const String timeURL = "http://some.url.com/timescript.php";
- const int Led = 5;
- const int relayPin = 13;
- // Lights On Schedule
- const int schedule[24] = {0, 0, 0, 0, 0, 0, 0, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 0, 0};
- const int scheduleDigital[24] = {1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1};
- WiFiClient client;
- HTTPClient http;
- unsigned int currentHour = 0;
- unsigned long nextTimeSyncMillis = 0;
- int lastPWMState = 0;
- int lastDigitalState = LOW;
- void syncTime() {
- // Reset every 45 days to make sure the millis() count doesn't overflow
- // Yes, this is hacky, but it's easy and effective.
- if (millis() > 3888000000)
- ESP.reset();
- http.begin(client, timeURL);
- int httpCode = http.GET();
- if (httpCode != 200) {
- Serial.println("Time sync failed! Could not contact time service URL!");
- return;
- }
- unsigned int currentMinutesIntoDay = http.getString().toInt();
- currentHour = currentMinutesIntoDay / 60;
- nextTimeSyncMillis = millis() + ((61 - (currentMinutesIntoDay % 60)) * 60000);
- Serial.print("Time Sync Successful. Current Hour: ");
- Serial.print(currentHour);
- Serial.print(" Next Sync: ");
- Serial.println(nextTimeSyncMillis);
- }
- void setup() {
- Serial.begin(115200);
- WiFi.begin(SSID, WiFiPass);
- while (WiFi.status() != WL_CONNECTED) {
- delay(1000);
- Serial.print("Connecting to WiFi...");
- }
- Serial.println("Connected to WiFi!");
- syncTime();
- pinMode(Led, OUTPUT);
- analogWrite(Led, 0);
- pinMode(relayPin, OUTPUT);
- digitalWrite(relayPin, LOW);
- }
- void loop() {
- if (millis() >= nextTimeSyncMillis)
- syncTime();
- if (schedule[currentHour] != lastPWMState) {
- analogWrite(Led, schedule[currentHour]);
- lastPWMState = schedule[currentHour];
- Serial.print("Setting PWM to: ");
- Serial.println(lastPWMState);
- }
- if (scheduleDigital[currentHour] != lastDigitalState) {
- digitalWrite(relayPin, scheduleDigital[currentHour]);
- lastDigitalState = scheduleDigital[currentHour];
- Serial.print("Setting Relay to: ");
- Serial.println(lastDigitalState);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement