如何在 ESP32 上设置静态 IP 地址
TL;DR
在调用 WiFi.begin(...) 之前,调用此代码:
how-to-set-static-ip-address-on-esp32.cpp
if (!WiFi.config(
IPAddress(192, 168, 19, 5), // ESP 的 IP 地址
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");
}并将 IP 地址等替换为静态
完整示例
这基于我们之前的文章如何修复 ESP32 不连接 Wifi 网络:
esp32_set_static_ip_example.cpp
#include <Arduino.h>
#include <WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.begin("MyWifiSSID", "MyWifiPassword");
// 设置静态 IP
if (!WiFi.config(
IPAddress(192, 168, 19, 5), // ESP 的 IP 地址
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");
}
// 等待 wifi 连接
uint32_t notConnectedCounter = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.println("Wifi connecting...");
notConnectedCounter++;
if(notConnectedCounter > 150) { // 5s 后未连接则重置板
Serial.println("Resetting due to Wifi not connecting...");
ESP.restart();
}
}
Serial.print("Wifi connected, IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// 将你的主要代码放在这里,重复运行:
}Check out similar posts by category:
Embedded, ESP8266/ESP32, Networking
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow