Movatterモバイル変換


[0]ホーム

URL:


Skip to content
HOMEESP32ESP8266ESP32-CAMRASPBERRY PIMICROPYTHONRPi PICOARDUINOREVIEWS

ESP8266 NodeMCU Static/Fixed IP Address (Arduino IDE)

This tutorial shows how to set a static/fixed IP address for your ESP8266 NodeMCU board. If you’re running a web server or Wi-Fi client with your ESP8266 and every time you restart your board, it has a new IP address, you can follow this tutorial to assign a static/fixed IP address.

Set ESP8266 NodeMCU Static or Fixed IP Address using Arduino IDE

Static/Fixed IP Address Sketch

To show you how to fix your ESP8266 IP address, we’ll use theESP8266 Web Sever code as an example. By the end of our explanation you should be able to fix your IP address regardless of the web server or Wi-Fi project you’re building.

Copy the code below to your Arduino IDE, but don’t upload it yet. You need to make some changes to make it work for you.

Note: if you upload the next sketch to your ESP8266 board, it should automatically assign the fixed IP address192.168.1.184.

/*********  Rui Santos  Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-static-fixed-ip-address-arduino/*********/// Load Wi-Fi library#include <ESP8266WiFi.h>// Replace with your network credentialsconst char* ssid     = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";// Set web server port number to 80WiFiServer server(80);// Variable to store the HTTP requestString header;// Auxiliar variables to store the current output stateString output5State = "off";String output4State = "off";// Assign output variables to GPIO pinsconst int output5 = 5;const int output4 = 4;// Current timeunsigned long currentTime = millis();// Previous timeunsigned long previousTime = 0; // Define timeout time in milliseconds (example: 2000ms = 2s)const long timeoutTime = 2000;// Set your Static IP addressIPAddress local_IP(192, 168, 1, 184);// Set your Gateway IP addressIPAddress gateway(192, 168, 1, 1);IPAddress subnet(255, 255, 0, 0);IPAddress primaryDNS(8, 8, 8, 8);   //optionalIPAddress secondaryDNS(8, 8, 4, 4); //optionalvoid setup() {  Serial.begin(115200);  // Initialize the output variables as outputs  pinMode(output5, OUTPUT);  pinMode(output4, OUTPUT);  // Set outputs to LOW  digitalWrite(output5, LOW);  digitalWrite(output4, LOW);    // Configures static IP address  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {    Serial.println("STA Failed to configure");  }    // Connect to Wi-Fi network with SSID and password  Serial.print("Connecting to ");  Serial.println(ssid);  WiFi.begin(ssid, password);  while (WiFi.status() != WL_CONNECTED) {    delay(500);    Serial.print(".");  }  // Print local IP address and start web server  Serial.println("");  Serial.println("WiFi connected.");  Serial.println("IP address: ");  Serial.println(WiFi.localIP());  server.begin();}void loop(){  WiFiClient client = server.available();   // Listen for incoming clients  if (client) {                             // If a new client connects,    Serial.println("New Client.");          // print a message out in the serial port    String currentLine = "";                // make a String to hold incoming data from the client    currentTime = millis();    previousTime = currentTime;    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected      currentTime = millis();               if (client.available()) {             // if there's bytes to read from the client,        char c = client.read();             // read a byte, then        Serial.write(c);                    // print it out the serial monitor        header += c;        if (c == '\n') {                    // if the byte is a newline character          // if the current line is blank, you got two newline characters in a row.          // that's the end of the client HTTP request, so send a response:          if (currentLine.length() == 0) {            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)            // and a content-type so the client knows what's coming, then a blank line:            client.println("HTTP/1.1 200 OK");            client.println("Content-type:text/html");            client.println("Connection: close");            client.println();                        // turns the GPIOs on and off            if (header.indexOf("GET /5/on") >= 0) {              Serial.println("GPIO 5 on");              output5State = "on";              digitalWrite(output5, HIGH);            } else if (header.indexOf("GET /5/off") >= 0) {              Serial.println("GPIO 5 off");              output5State = "off";              digitalWrite(output5, LOW);            } else if (header.indexOf("GET /4/on") >= 0) {              Serial.println("GPIO 4 on");              output4State = "on";              digitalWrite(output4, HIGH);            } else if (header.indexOf("GET /4/off") >= 0) {              Serial.println("GPIO 4 off");              output4State = "off";              digitalWrite(output4, LOW);            }                        // Display the HTML web page            client.println("<!DOCTYPE html><html>");            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");            client.println("<link rel=\"icon\" href=\"data:,\">");            // CSS to style the on/off buttons             // Feel free to change the background-color and font-size attributes to fit your preferences            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");            client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;");            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");            client.println(".button2 {background-color: #77878A;}</style></head>");                        // Web Page Heading            client.println("<body><h1>ESP8266 Web Server</h1>");                        // Display current state, and ON/OFF buttons for GPIO 5              client.println("<p>GPIO 5 - State " + output5State + "</p>");            // If the output5State is off, it displays the ON button                   if (output5State=="off") {              client.println("<p><a href=\"/5/on\"><button class=\"button\">ON</button></a></p>");            } else {              client.println("<p><a href=\"/5/off\"><button class=\"button button2\">OFF</button></a></p>");            }                            // Display current state, and ON/OFF buttons for GPIO 4              client.println("<p>GPIO 4 - State " + output4State + "</p>");            // If the output4State is off, it displays the ON button                   if (output4State=="off") {              client.println("<p><a href=\"/4/on\"><button class=\"button\">ON</button></a></p>");            } else {              client.println("<p><a href=\"/4/off\"><button class=\"button button2\">OFF</button></a></p>");            }            client.println("</body></html>");                        // The HTTP response ends with another blank line            client.println();            // Break out of the while loop            break;          } else { // if you got a newline, then clear currentLine            currentLine = "";          }        } else if (c != '\r') {  // if you got anything else but a carriage return character,          currentLine += c;      // add it to the end of the currentLine        }      }    }    // Clear the header variable    header = "";    // Close the connection    client.stop();    Serial.println("Client disconnected.");    Serial.println("");  }}

View raw code

Setting Your Network Credentials

You need to modify the following lines with your network credentials: SSID and password.

// Replace with your network credentialsconst char* ssid = "REPLACE_WITH_YOUR_SSID";const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Setting ESP8266 Static IP Address

Then, outside thesetup() andloop() functions, you define the following variables with your own static IP address and corresponding gateway IP address.

By default, the next code assigns the IP address192.168.1.184 that works in the gateway192.168.1.1.

// Set your Static IP addressIPAddress local_IP(192, 168, 1, 184);// Set your Gateway IP addressIPAddress gateway(192, 168, 1, 1);IPAddress subnet(255, 255, 0, 0);IPAddress primaryDNS(8, 8, 8, 8); // optionalIPAddress secondaryDNS(8, 8, 4, 4); // optional

Important: you need to use an available IP address in your local network and the corresponding gateway.

setup()

In thesetup() you need to call theWiFi.config() method to assign the configurations to your ESP8266.

// Configures static IP addressif (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {  Serial.println("STA Failed to configure");}

Note: theprimaryDNSandsecondaryDNSparameters are optional and you can remove them.

Testing

After uploading the code to your board, open the Arduino IDE Serial Monitor at the baud rate 115200, restart your ESP8266 board and the IP address defined earlier should be assigned to your board.

ESP8266 Fixed Static IP Address Serial Monitor

As you can see, it prints the IP address192.168.1.184.

You can take this example and add it to all your Wi-Fi sketches to assign a fixed IP address to your ESP8266.

Assigning IP Address with MAC Address

If you’ve tried to assign a fixed IP address to the ESP8266 using the previous example and it doesn’t work, we recommend assigning an IP address directly in your router settings through theESP8266 MAC Address.

Upload the following code to the ESP8266 board:

/*  Rui Santos & Sara Santos - Random Nerd Tutorials  Complete project details at https://RandomNerdTutorials.com/get-change-esp32-esp8266-mac-address-arduino/  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.    The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.*/#ifdef ESP32  #include <WiFi.h>  #include <esp_wifi.h>#else  #include <ESP8266WiFi.h>#endifvoid setup(){  Serial.begin(115200);  Serial.print("ESP Board MAC Address: ");  #ifdef ESP32    WiFi.mode(WIFI_STA);    WiFi.STA.begin();    uint8_t baseMac[6];    esp_err_t ret = esp_wifi_get_mac(WIFI_IF_STA, baseMac);    if (ret == ESP_OK) {      Serial.printf("%02x:%02x:%02x:%02x:%02x:%02x\n",                    baseMac[0], baseMac[1], baseMac[2],                    baseMac[3], baseMac[4], baseMac[5]);    } else {      Serial.println("Failed to read MAC address");    }  #else    Serial.println(WiFi.macAddress());  #endif} void loop(){}

View raw code

In thesetup(), it prints the ESP8266 MAC Address in the Serial Monitor:

// Print ESP MAC AddressSerial.println("MAC address: ");Serial.println(WiFi.macAddress());

In our case, the ESP8266 MAC Address isB4:E6:2D:97:EE:F1. Copy the MAC Address, because you’ll need it in just a moment.

Router Settings

If you login into your router admin page, there should be a page/menu where you can assign an IP address to a network device. Each router has different menus and configurations. So, we can’t provide instructions on how do to it for all the available routers.

We recommend Googling “assign IP address to MAC address” followed by your router name. You should find some instructions that show how to assign the IP to a MAC address for your specific router.

In summary, if you go to your router configurations menu, you should be able to assign your desired IP address to your ESP8266 MAC address (for example B4:E6:2D:97:EE:F1).

Wrapping Up

After following this tutorial you should be able to assign a fixed/static IP address to your ESP8266. If you have an ESP32, you can read this guideSet ESP32 Static/Fixed IP Address.

We hope you’ve found this tutorial useful. If you like ESP8266, you may also like:

Thanks for reading.



SMART HOME with Raspberry Pi ESP32 and ESP8266 Node-RED InfluxDB eBook
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

29 thoughts on “ESP8266 NodeMCU Static/Fixed IP Address (Arduino IDE)”

  1. Thanks for the code Sara. Good like always.

    Reply
  2. Thanks a lot.

    Reply
  3. You make my Day. 🙂
    Hands in the air for you
    Regards
    / Peter
    (Sweden)

    Reply
  4. Thank you very much for such excellent tutorials, I would like to know how you can configure the ESP parameters (ssid, pass and fixed ip) from a page or application

    Reply
  5. hello how to get gateway address and set the ip address according to it. i mean if gateway is 192.168.0.1 then local ip should be 192.168.0.2 and if gateway is 192.168.1.1 then local ip should be 192.168.1.2,plz help

    Reply
  6. Thanks a lot for your tutorials, they are always a great help for me.
    This time I’ve a problem and maybe you know how to fix it.
    I loaded in my NodeMCU your code and, if my router is turned on, it works perfectly.
    What is strange is that, if my router is turned off, the board send to the serial monitor the same message as il was connected to the router, and this is obviosly impossible.
    Any idea will be apreciate…
    Thanks again.

    Reply
  7. your tutorials are just awesome, informative, and well documented.thank you so much for sharing the knowledge. I wish you the best of luck in all that you do.

    Reply
  8. Thank you for your useful tutorials!

    However, I had a problem with this one: whenever I used a static IP configuration, connection would fail. The ESP8266 would get an IP address but fail to connect to a host. The problem was the ‘subnet’ parameter, which – on my setup – should be the local subnetaddress, not the netmask. For example, if all of your hosts are on 192.168.1.x then ‘subnet’ should be 192.168.1.0. It all worked fine after I changed that tiny thing. I reckon that most people use dynamic IP addresses, or someone would surely have spotted this.

    Reply
  9. First, it not worked when I have written “WiFi.config” below “while (WiFi.status() != WL_CONNECTED)”, after assuming that the MCU executes instructions from up to down, the funny thing is that I heard that compiler verifies program from last to first line, so I used to think the same fom execution, whatever, then I shifed “WiFi.config” above and it worked but… this time It was not accessible I don’t know why, I think there are some protocols for IP, gateway, subnet, DNS etc., I had chnaged IP from 192.168.78.92 to 192.168.1.92 and it worked but I wanted to set it 78.92, but its okay, I know its possible, say me if you get time, thank you very much.

    Reply
  10. A bit of warning about using static IP without DNS servers. I found that ezTime NTP library do not work if there is no DNS provided, probably do not lookup for ntp servers, so keep it in mind while setting static IP

    Reply
  11. I wonder if the new routers have become more critical with connection of new devices. This static IP helps with my new router, but then I cannot get connection to Gmail SMTP server.

    Reply
  12. Hi there guys, the code is uploading to my board correctly but it’s just not showing me the IP address like it fails to connect to the Wi-Fi, it was worked once before so I know it is possible but no matter how many tries it’s not working again.
    -Yes I’ve checked the baud rate for the serial monitor
    -Yes my password and SSID is correct

    I need to get this to work for a school project. Your tutorials have been very helpful so far and I’m quite annoyed that I didn’t find it sooner!!

    Reply
    • Hi.
      If you are absolutely sure that credentials are ok, check that the board is relatively close to the Wi-Fi router.
      Reset the board a couple of times after it fails to connect to Wi-Fi.
      Regards,
      Sara

      Reply
  13. Hiii, im using a websocket server on nodemcu connecting to a website. When im running the client code on the same computer connected to same wifi it works but when it’s connected to a different wifi im getting and error and I’m not able to connect to the server that is on nodemcu. Do you have any solution for it?

    Reply
  14. Hi,I’m 14 from Taiwan,Thank you so much for your tutorial ,could you tell me if this will also work in AP mode?Thanks!

    Reply
  15. uploade-connected to wifi too but when load the local adress unable to connect and program html page never loaded

    Reply
  16. Hi, I want to add this to another tutorial of yours namely: ESP8266 NodeMCU Relay Module – Control AC Appliances (Web Server)
    However, I receive many errors, guessing it is code clashing. I need to control appliances from my website but the IPs keeps changing

    Reply
  17. Hi and thanks for the tutorial. A question, though. When you upload your next sketch to your ESP8266, is it not going to wipe out the previous sketch that was used to set the static IP?
    Thanks for clearing this up!
    Doug

    Reply

Leave a CommentCancel reply

Learn ESP8266

ESP8266 Introduction

ESP8266 Arduino IDE

ESP8266 Arduino IDE 2.0

VS Code and PlatformIO

ESP8266 Pinout

ESP8266 Inputs Outputs

ESP8266 PWM

ESP8266 Analog Inputs

ESP8266 Interrupts Timers

ESP8266 Deep Sleep

Protocols

ESP8266 Web Server

ESP8266 MQTT

ESP8266 ESP-NOW

ESP8266 Wi-Fi

ESP8266 WebSocket

ESP8266 ESP-MESH

ESP8266 Email

ESP8266 HTTP GET POST

HTTP GET Web APIs

HTTP POST Web APIs

ESP-NOW One-to-Many

ESP-NOW Many-to-One

ESP-NOW Two-Way

ESP-NOW ESP8266 + ESP32

ESP-NOW + Wi-Fi Web Server

Server-Sent Events

Web Servers

Output Web Server

PWM Slider Web Server

PWM Multiple Sliders Web Server

Async Web Server

Relay Web Server

DHT Web Server

BME280 Web Server

BME680 Web Server

DS18B20 Web Server

Plot/Chart Web Server

Chart Multiple Series Web Server

SPIFFS Web Server

Thermostat Web Server

Input Fields Web Server

Images Web Server

RGB LED Web Server

Momentary Switch Web Server

Physical Button Web Server

Timer/Pulse Web Server

Gauges Web Server

HTTP Auth Web Server

ESP8266 WiFiManager

Stepper Motor WebSocket

DIY Cloud

ESP8266 Weather Station

Control GPIOs

View Sensor Readings

ESP8266 MySQL

ESP8266 PHP Email

Cloud Node-RED Dashboard

Cloud MQTT Broker

Firebase

Firebase Realtime Database

Firebase Web App

Firebase Authentication

Firebase BME280

Firebase Web App Sensor Readings

Modules and Sensors

ESP8266 Relay Module

ESP8266 PIR

ESP8266 HC-SR04

ESP8266 AC PIR

ESP8266 Reed Switch

ESP8266 DHT11/DHT22

ESP8266 BME280

ESP8266 BME680

ESP8266 DS18B20

ESP8266 BMP388

ESP8266 Mains Voltage

ESP8266 Stepper Motor

ESP8266 I2C Multiplexer

Displays

ESP8266 OLED

ESP8266 LCD

ESP8266 Nextion

OLED Temperature

MQTT

ESP8266 MQTT

MQTT Output RPi

MQTT DHT RPi

MQTT SQLite RPi

MQTT DHT11/DHT22

MQTT BME280

MQTT BME680

MQTT DS18B20

ESP8266 MPU-6050

Other Projects

ESP8266 Alexa

ESP8266 Google Sheets

Multisensor Shield

Multisensor Shield Node-RED

ESP8266 Daily Task

ESP8266 Wi-Fi Button

Latching Power Circuit

Telegram Control Outputs

Telegram Sensor Readings

Telegram Detect Motion

Telegram Group

Telegram Door Monitor

ESP8266 WebSerial

Useful Guides

ESP8266 Troubleshooting

ESP8266 Access Point

ESP8266 Fixed IP Address

ESP8266 MAC Address

ESP8266 Reconnect Wi-Fi

ESP8266 Hostname

ESP8266 OTA

ESP8266 OTA Arduino

ESP8266 OTA VS Code

ESP8266 Solar Panels

ESP8266 Voltage Regulator

ESP8266 ThingSpeak

ESP8266 Install SPIFFS

ESP8266 Install LittleFS

ESP8266 Time and Date

ESP8266 Epoch Time

ESP8266 JSON

VS Code and PlatformIO

VS Code LittleFS

VS Code Workspaces

Learn More

Learn ESP32

Learn ESP8266

Learn ESP32-CAM

Learn MicroPython

Learn Arduino

Build Web Servers eBook

ESP8266 eBook »

Affiliate Disclosure:Random Nerd Tutorials is a participant in affiliate advertising programs designed to provide a means for us to earn fees by linking to Amazon, eBay, AliExpress, and other sites. We might be compensated for referring traffic and business to these companies.



Learn ESP32 with Arduino IDE eBook » Complete guide to program the ESP32 with Arduino IDE!



SMART HOME with Raspberry Pi, ESP32, and ESP8266 » learn how to build a complete home automation system.



Learn Raspberry Pi Pico/Pico W with MicroPython​ » The complete getting started guide to get the most out of the the Raspberry Pi Pico/Pico W (RP2040) microcontroller board using MicroPython programming language.



🔥 Learn LVGL: Build GUIs for ESP32 Projects​ » Learn how to build Graphical User Interfaces (GUIs) for ESP32 Projects using LVGL (Light Versatile Graphics Library) with the Arduino IDE.

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.


[8]ページ先頭

©2009-2025 Movatter.jp