Created
January 20, 2025 14:13
-
-
Save josezy/1969532fe44dcefcc2de0cf20c49d953 to your computer and use it in GitHub Desktop.
Arduino example script to test ESP32 WiFi connectivity. Meant to quickly test routers' connectivity
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 <WiFi.h> | |
#include <HTTPClient.h> // Add HTTP client library | |
const char *ssid = "<YOUR_SSID>"; | |
const char *password = "<YOUR_PASSWORD>"; | |
int btnGPIO = 0; | |
int btnState = false; | |
// Function to test internet connectivity | |
bool testInternetConnection() { | |
HTTPClient http; | |
// Try to connect to Google's homepage | |
http.begin("http://www.google.com"); | |
int httpCode = http.GET(); | |
Serial.print("[HTTP] Testing internet connectivity... "); | |
if (httpCode > 0) { | |
Serial.println("CONNECTED"); | |
Serial.printf("[HTTP] Status code: %d\n", httpCode); | |
http.end(); | |
return true; | |
} else { | |
Serial.println("FAILED"); | |
Serial.printf("[HTTP] Error: %s\n", http.errorToString(httpCode).c_str()); | |
http.end(); | |
return false; | |
} | |
} | |
void setup() { | |
Serial.begin(115200); | |
delay(10); | |
pinMode(btnGPIO, INPUT); | |
Serial.println(); | |
Serial.print("[WiFi] Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, password); | |
int tryDelay = 500; | |
int numberOfTries = 20; | |
while (true) { | |
switch (WiFi.status()) { | |
case WL_NO_SSID_AVAIL: | |
Serial.println("[WiFi] SSID not found"); | |
break; | |
case WL_CONNECT_FAILED: | |
Serial.print("[WiFi] Failed - WiFi not connected! Reason: "); | |
return; | |
break; | |
case WL_CONNECTION_LOST: | |
Serial.println("[WiFi] Connection was lost"); | |
break; | |
case WL_SCAN_COMPLETED: | |
Serial.println("[WiFi] Scan is completed"); | |
break; | |
case WL_DISCONNECTED: | |
Serial.println("[WiFi] WiFi is disconnected"); | |
break; | |
case WL_CONNECTED: | |
Serial.println("[WiFi] WiFi is connected!"); | |
Serial.print("[WiFi] IP address: "); | |
Serial.println(WiFi.localIP()); | |
// Test internet connectivity once connected | |
testInternetConnection(); | |
return; | |
break; | |
default: | |
Serial.print("[WiFi] WiFi Status: "); | |
Serial.println(WiFi.status()); | |
break; | |
} | |
delay(tryDelay); | |
if (numberOfTries <= 0) { | |
Serial.print("[WiFi] Failed to connect to WiFi!"); | |
WiFi.disconnect(); | |
return; | |
} else { | |
numberOfTries--; | |
} | |
} | |
} | |
void loop() { | |
btnState = digitalRead(btnGPIO); | |
if (btnState == LOW) { | |
Serial.println("[WiFi] Disconnecting from WiFi!"); | |
if (WiFi.disconnect(true, false)) { | |
Serial.println("[WiFi] Disconnected from WiFi!"); | |
} | |
delay(1000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment