How to ping gateway in ESP32
You can use the ESP32Ping library in order to easily ping the current gateway IP:
if(Ping.ping(WiFi.gatewayIP(), 1)) { // 1: Just one ping
// TODO What to do on ping succes
// Example: Print response time
Serial.print(Ping.averageTime()); // Unit: ms
Serial.println(" ms");
} else {
// TODO What to do if ping failed?
}
Full example:
#include <Arduino.h>
#include <WiFi.h>
#include <ESP32Ping.h>
void waitForWiFiConnectOrReboot(bool printOnSerial=true) {
uint32_t notConnectedCounter = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(100);
if(printOnSerial) {
Serial.println("Wifi connecting...");
}
notConnectedCounter++;
if(notConnectedCounter > 50) { // Reset board if not connected after 5s
if(printOnSerial) {
Serial.println("Resetting due to Wifi not connecting...");
}
ESP.restart();
}
}
if(printOnSerial) {
// Print wifi IP addess
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
}
#define LED_BUILTIN 2
void setup() {
Serial.begin(115200);
WiFi.begin("MyWifiSSID", "MyWifiPassword");
// Wait for wifi to be connected
waitForWiFiConnectOrReboot();
// Initialize LED
pinMode(LED_BUILTIN,OUTPUT);
}
void loop() {
if(Ping.ping(WiFi.gatewayIP())) {
digitalWrite(LED_BUILTIN,HIGH);
Serial.print(Ping.averageTime());
Serial.println(" ms");
} else {
digitalWrite(LED_BUILTIN, LOW);
Serial.println("Error :(");
}
}
Example output
6.12 ms
5.12 ms
5.11 ms
5.16 ms
4.95 ms
4.88 ms
4.84 ms
7.67 ms
5.01 ms
4.87 ms
4.81 ms
4.80 ms
4.85 ms
5.08 ms
5.76 ms
4.54 ms
5.12 ms
2.77 ms
4.88 ms
4.84 ms
6.07 ms
5.08 ms
4.91 ms
6.04 ms
4.88 ms
4.98 ms
6.43 ms
8.18 ms
4.93 ms
5.17 ms
4.97 ms
5.46 ms
5.88 ms
4.78 ms
4.88 ms
6.03 ms
4.84 ms
5.70 ms
5.94 ms
7.25 ms
5.07 ms
4.78 ms
5.51 ms
4.99 ms
5.04 ms
4.79 ms
4.94 ms
4.81 ms
5.97 ms
5.85 ms
4.83 ms
4.80 ms
4.80 ms
6.29 ms
4.99 ms
5.04 ms
9.21 ms
5.20 ms
6.05 ms
6.14 ms
5.03 ms
4.90 ms
7.22 ms
5.06 ms
4.94 ms
9.03 ms
5.13 ms
11.97 ms
6.32 ms
6.12 ms
4.92 ms
4.92 ms
6.01 ms
4.96 ms
4.98 ms
4.94 ms
6.08 ms
6.11 ms
4.93 ms
5.05 ms
5.78 ms
4.47 ms
6.28 ms
5.02 ms
5.13 ms
5.11 ms
5.19 ms
8.89 ms
5.76 ms
5.18 ms
8.08 ms
4.97 ms
4.89 ms
4.70 ms
5.40 ms
7.46 ms
5.09 ms
4.95 ms
4.96 ms
5.01 ms
5.01 ms
4.89 ms
6.22 ms
6.76 ms
6.92 ms
6.10 ms
9.61 ms
5.29 ms
6.13 ms
5.15 ms
5.02 ms
5.03 ms
5.01 ms
6.13 ms
4.78 ms
3.90 ms
6.27 ms
8.07 ms
5.94 ms
4.50 ms
6.13 ms
4.99 ms
6.07 ms
4.80 ms
4.84 ms
4.95 ms
4.95 ms
6.78 ms
4.88 ms