PlowmanPlow

FishTime

Jan 13th, 2021
721
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <Arduino.h>
  2. #include <ESP8266HTTPClient.h>
  3. #include <ESP8266WiFi.h>
  4.  
  5. #include <string>
  6.  
  7. const char *SSID = "SSID";
  8. const char *WiFiPass = "pwkey";
  9. const String timeURL = "http://some.url.com/timescript.php";
  10. const int Led = 5;
  11. const int relayPin = 13;
  12.  
  13. // Lights On Schedule
  14. 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};
  15. 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};
  16.  
  17. WiFiClient client;
  18. HTTPClient http;
  19. unsigned int currentHour = 0;
  20. unsigned long nextTimeSyncMillis = 0;
  21. int lastPWMState = 0;
  22. int lastDigitalState = LOW;
  23.  
  24. void syncTime() {
  25.     // Reset every 45 days to make sure the millis() count doesn't overflow
  26.     // Yes, this is hacky, but it's easy and effective.
  27.     if (millis() > 3888000000)
  28.         ESP.reset();
  29.     http.begin(client, timeURL);
  30.     int httpCode = http.GET();
  31.     if (httpCode != 200) {
  32.         Serial.println("Time sync failed! Could not contact time service URL!");
  33.         return;
  34.     }
  35.     unsigned int currentMinutesIntoDay = http.getString().toInt();
  36.     currentHour = currentMinutesIntoDay / 60;
  37.     nextTimeSyncMillis = millis() + ((61 - (currentMinutesIntoDay % 60)) * 60000);
  38.     Serial.print("Time Sync Successful. Current Hour: ");
  39.     Serial.print(currentHour);
  40.     Serial.print("  Next Sync: ");
  41.     Serial.println(nextTimeSyncMillis);
  42. }
  43.  
  44. void setup() {
  45.     Serial.begin(115200);
  46.     WiFi.begin(SSID, WiFiPass);
  47.     while (WiFi.status() != WL_CONNECTED) {
  48.         delay(1000);
  49.         Serial.print("Connecting to WiFi...");
  50.     }
  51.     Serial.println("Connected to WiFi!");
  52.     syncTime();
  53.     pinMode(Led, OUTPUT);
  54.     analogWrite(Led, 0);
  55.     pinMode(relayPin, OUTPUT);
  56.     digitalWrite(relayPin, LOW);
  57. }
  58.  
  59. void loop() {
  60.     if (millis() >= nextTimeSyncMillis)
  61.         syncTime();
  62.     if (schedule[currentHour] != lastPWMState) {
  63.         analogWrite(Led, schedule[currentHour]);
  64.         lastPWMState = schedule[currentHour];
  65.         Serial.print("Setting PWM to: ");
  66.         Serial.println(lastPWMState);
  67.     }
  68.     if (scheduleDigital[currentHour] != lastDigitalState) {
  69.         digitalWrite(relayPin, scheduleDigital[currentHour]);
  70.         lastDigitalState = scheduleDigital[currentHour];
  71.         Serial.print("Setting Relay to: ");
  72.         Serial.println(lastDigitalState);
  73.     }
  74. }
  75.  
RAW Paste Data