1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| #include <WiFi.h> #include <NTPClient.h> #include <WiFiUdp.h> #include <Adafruit_NeoPixel.h>
const char* ssid = "wifi名稱"; const char* password = "密碼";
const char* ntpServer = "asia.pool.ntp.org"; const long utcOffsetInSeconds = 8 * 3600;
WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, ntpServer, utcOffsetInSeconds);
#define LED_PIN 5 #define NUM_LEDS 60 #define LED_BRIGHTNESS 5 Adafruit_NeoPixel strip(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
unsigned long previousMillis = 0; const long interval = 1000; int hour = 0; int minute = 0; int second = 0;
void setup() { Serial.begin(115200); strip.begin(); strip.show(); unsigned long startAttemptTime = millis(); while (WiFi.status() != WL_CONNECTED && (millis() - startAttemptTime) < 40000) { WiFi.begin(ssid, password); delay(1000); Serial.println("正在連接WiFi..."); } if (WiFi.status() != WL_CONNECTED) { for (int i = 0; i < NUM_LEDS; i++) { strip.setPixelColor(i, strip.Color(255, 0, 0)); } strip.show(); delay(2000); hour = 8; minute = 0; second = 0; } else { timeClient.begin(); timeClient.update(); hour = timeClient.getHours(); minute = timeClient.getMinutes(); second = timeClient.getSeconds(); } }
void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; if (WiFi.status() == WL_CONNECTED) { timeClient.update(); hour = timeClient.getHours(); minute = timeClient.getMinutes(); second = timeClient.getSeconds(); } else { second = (second + 1) % 60; if (second == 0) { minute = (minute + 1) % 60; if (minute == 0) { hour = (hour + 1) % 24; } } } updateLEDs(); } }
void updateLEDs() { int hourIndex = (hour % 24) * 2.5; int minuteIndex = minute; int secondIndex = second;
strip.clear();
for (int i = hourIndex; i < hourIndex + 5; i++) { int ledIndex = (NUM_LEDS - 1 - i); if (ledIndex >= 0 && ledIndex < NUM_LEDS) { strip.setPixelColor(ledIndex, strip.Color(255, 0, 0)); } }
int minuteLedIndex = (NUM_LEDS - 1 - minuteIndex); if (minuteLedIndex >= 0 && minuteLedIndex < NUM_LEDS) { strip.setPixelColor(minuteLedIndex, strip.Color(0, 255, 0)); }
int secondLedIndex = (NUM_LEDS - 1 - secondIndex); if (secondLedIndex >= 0 && secondLedIndex < NUM_LEDS) { strip.setPixelColor(secondLedIndex, strip.Color(0, 0, 255)); }
strip.show(); }
|