TL;DR
Before you call WiFi.begin(...)
, call this:
if (!WiFi.config( IPAddress(192, 168, 19, 5), // ESP's IP address IPAddress(192, 168, 19, 1), // Gateway IPAddress(255, 255, 255, 0), // IP Address IPAddress(192, 168, 19, 1) // DNS server )) { Serial.println("Failed to set static IP"); }
and replace the IP address etc with the static
Full example
This is based on our previous post on How to fix ESP32 not connecting to the Wifi network:
#include <Arduino.h> #include <WiFi.h> void setup() { Serial.begin(115200); WiFi.begin("MyWifiSSID", "MyWifiPassword"); // Set static IP if (!WiFi.config( IPAddress(192, 168, 19, 5), // ESP's IP address IPAddress(192, 168, 19, 2), // Gateway IPAddress(255, 255, 255, 0), // IP Address IPAddress(192, 168, 19, 1) // DNS server )) { Serial.println("Failed to set static IP"); } // Wait for wifi to be connected uint32_t notConnectedCounter = 0; while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.println("Wifi connecting..."); notConnectedCounter++; if(notConnectedCounter > 150) { // Reset board if not connected after 5s Serial.println("Resetting due to Wifi not connecting..."); ESP.restart(); } } Serial.print("Wifi connected, IP address: "); Serial.println(WiFi.localIP()); } void loop() { // put your main code here, to run repeatedly: }