Created
May 13, 2025 15:30
-
-
Save pccr10001/4c1b34447b8e09da7d16d7a6e1f749e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#include <ESP8266Ping.h> | |
// WiFi設定 | |
const char* ssid = "AAA"; | |
const char* password = "8888888"; | |
// 計時變數 | |
unsigned long previousPingMillis = 0; | |
unsigned long previousReconnectMillis = 0; | |
const unsigned long pingInterval = 10000; // 10秒 | |
const unsigned long reconnectCheckInterval = 5000; // 5秒 | |
// Gateway IP地址 | |
IPAddress gatewayIP; | |
// 連接WiFi的函數 | |
void connectToWiFi() { | |
Serial.print("連接WiFi網路: "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, password); | |
// 等待連接 | |
int attempts = 0; | |
while (WiFi.status() != WL_CONNECTED && attempts < 20) { | |
delay(500); | |
Serial.print("."); | |
attempts++; | |
} | |
if (WiFi.status() == WL_CONNECTED) { | |
Serial.println("\nWiFi已連接"); | |
Serial.print("IP地址: "); | |
Serial.println(WiFi.localIP()); | |
// 獲取Gateway IP | |
gatewayIP = WiFi.gatewayIP(); | |
Serial.print("Gateway IP: "); | |
Serial.println(gatewayIP.toString()); | |
// 設置自動重連 | |
WiFi.setAutoReconnect(true); | |
WiFi.persistent(true); | |
} else { | |
Serial.println("\n無法連接WiFi,稍後重試..."); | |
} | |
} | |
void setup() { | |
Serial.begin(115200); | |
delay(1000); | |
Serial.println("\nESP8266 WiFi Ping程式"); | |
// 連接WiFi | |
connectToWiFi(); | |
} | |
void loop() { | |
unsigned long currentMillis = millis(); | |
// 檢查WiFi狀態並在必要時重新連接(每5秒) | |
if (currentMillis - previousReconnectMillis >= reconnectCheckInterval) { | |
previousReconnectMillis = currentMillis; | |
if (WiFi.status() != WL_CONNECTED) { | |
Serial.println("WiFi連接斷開,正在重新連接..."); | |
connectToWiFi(); | |
} | |
} | |
// 每10秒ping一次gateway | |
if (currentMillis - previousPingMillis >= pingInterval && WiFi.status() == WL_CONNECTED) { | |
previousPingMillis = currentMillis; | |
Serial.print("Ping Gateway ("); | |
Serial.print(gatewayIP.toString()); | |
Serial.println(")..."); | |
// 發送ping封包(不關心回應,根據需求) | |
Ping.ping(gatewayIP, 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment