Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed IP with ESP8266WiFi #1959

Closed
SamirTafesh opened this issue Apr 21, 2016 · 23 comments

Comments

@SamirTafesh
Copy link

@SamirTafesh SamirTafesh commented Apr 21, 2016

Hello,

i am building a Relay controller via ESP8266Wifi, every thing works fine with no problem, but the issue is that every time i restart the ESP, a new IP address is assigned, i would like to know if it is possible to fix an IP address from the code and not from the router

the Code is

/*

  • This sketch demonstrates how to set up a simple HTTP-like server.
  • The server will set a GPIO pin depending on the request
  • http://server_ip/gpio/0 will set the GPIO2 low,
  • http://server_ip/gpio/1 will set the GPIO2 high
  • server_ip is the IP address of the ESP8266 module, will be
  • printed to Serial when the module is connected.
    */

include ESP8266WiFi.h

const char* ssid = "BOSS-HOME";
const char* password = "9876543210";
// the IP address for the shield:
IPAddress ip(192, 168, 1, 177);

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);

// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, HIGH);
pinMode(0, OUTPUT);
digitalWrite(0, HIGH);

// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

//WiFi.config(ip);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Start the server
server.begin();
Serial.println("Server started");

// Print the IP address
Serial.println(WiFi.localIP());
}

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

// Match the request
int val;
if (req.indexOf("/gpio/0") != -1)
digitalWrite(2, LOW);
else if (req.indexOf("/gpio/1") != -1)
digitalWrite(2,HIGH);
else {
Serial.println("invalid request");
client.stop();
return;
}

// Set GPIO2 according to the request
//digitalWrite(2, val);

client.flush();

// Prepare the response
String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\r\n\r\nGPIO is now ";
s += (val)?"high":"low";
s += "\n";

// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");

// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}

@t3chguy

This comment has been minimized.

Copy link

@t3chguy t3chguy commented Apr 21, 2016

As long as the DHCP Pool in your Router isn't the full subnet then yes you can, but if not then it'll have to be done on the router, and if you do not know what section of the subnet is not part of the Pool then you will have to do it from the Router anyway.

@SamirTafesh

This comment has been minimized.

Copy link
Author

@SamirTafesh SamirTafesh commented Apr 21, 2016

Thank you for the reply,
The DHCP pool is not full, so how can I fix an IP address from within the Code.
Regards
Samir Tafesh

@duncan-a

This comment has been minimized.

Copy link

@duncan-a duncan-a commented Apr 21, 2016

Try this, it works for me...

// config static IP
IPAddress ip(192, 168, 1, xx); // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // set gateway to match your network
Serial.print(F("Setting static ip to : "));
Serial.println(ip);
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your
network
WiFi.config(ip, gateway, subnet);

Your network may not be 192.168.1 based so, if not, change to suit. Also
note that the code separates with commas!!!

On 21 April 2016 at 18:29, Samir Tafesh notifications@github.com wrote:

Thank you for the reply,
The DHCP pool is not full, so how can I fix an IP address from within the
Code.
Regards
Samir Tafesh


You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub
#1959 (comment)

@SamirTafesh

This comment has been minimized.

Copy link
Author

@SamirTafesh SamirTafesh commented Apr 22, 2016

Dear Duncan,

Thank you for the Update, it worked fine,

Regards
Samir Tafesh

@annwinters

This comment has been minimized.

Copy link

@annwinters annwinters commented Aug 26, 2016

Just signed up to say... "Thanks"... it worked for me too...
Just adding the code below as being a near newbie, it took me a few tries to locate where I put the code!

#include <ESP8266WiFi.h>
#include <RCSwitch.h>
#include <IRremoteESP8266.h>

// NETWORK: Static IP details...
IPAddress ip(192, 168, 11, 23);
IPAddress gateway(192, 168, 11, 1);
IPAddress subnet(255, 255, 255, 0);


void setup() {
Serial.begin(115200);

Serial.print("Connecting to ");
Serial.println(ssid);

// Static IP Setup Info Here...
WiFi.config(ip, gateway, subnet);

// Start Server
WiFi.begin(ssid, password);


Thanks again... Your help is really appreciated.
Ann

@chathuraly

This comment has been minimized.

Copy link

@chathuraly chathuraly commented Dec 19, 2016

// Static IP details...
IPAddress ip(192, 168, 1, 222);
IPAddress gateway(192, 168, 1, 249);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(192, 168, 1, 249);

// Static IP Setup Info Here...
WiFi.config(ip, dns, gateway, subnet); //If you need Internet Access You should Add DNS also...
WiFi.begin(ssid, password);

@massimo2015

This comment has been minimized.

Copy link

@massimo2015 massimo2015 commented Jan 20, 2017

chathuraly, your code is working here too. I am working on ESP8266-01 and it gets more and more interesting as I go on coding.

@pradeepsysargus

This comment has been minimized.

Copy link

@pradeepsysargus pradeepsysargus commented Feb 7, 2017

how to set static ip address in #include "WiFiEsp.h" in arduino mega. serial3 port is connected to esp8266

@AnanthaSravani

This comment has been minimized.

Copy link

@AnanthaSravani AnanthaSravani commented Feb 10, 2017

Hi, we are working on ESP8266 wifi module with msp432 . i have a query using that.
the data which will be sent to the wifi module has to be visible on the web server or some console application. the application should be continuous listening mode.
can you please help me out on this.
Thank you in advance

@1an0wen

This comment has been minimized.

Copy link

@1an0wen 1an0wen commented Mar 5, 2017

Apologies, slightly off topic but does anyone know how I can make the local port static? i.e. push all comms through port 1234.

@vbarunn

This comment has been minimized.

Copy link

@vbarunn vbarunn commented Mar 10, 2017

Hi, the above-mentioned method to setup static IP is working with the home routers. However, with Mobile phone hotspot it is not working ... Any ideas? (I could connect to MQTT broker with static IP when using mobile phone AP)

@1an0wen

This comment has been minimized.

Copy link

@1an0wen 1an0wen commented Mar 10, 2017

@vbarunn similar problem here. Can't fix the IP and found that the IP address and port returned 0.0.0.0:0 was causing the problem for me. Once it is up and running I monitor the remote IP port and if it changes reset the ESP. Not ideal but for now it keeps the device working... something like if(client.remotePort() < 1){ESP.reset();}

@vasco65

This comment has been minimized.

Copy link

@vasco65 vasco65 commented Apr 4, 2017

I'm running in trouble trying to setup a fixed IP using an ESP-12 (node MCU v2) using arduino ide
I'm using the code published above (with different IP's)

// Static IP details...
IPAddress ip(192, 168, 1, 222);
IPAddress gateway(192, 168, 1, 249);
IPAddress subnet(255, 255, 255, 0);
IPAddress dns(192, 168, 1, 249);

// Static IP Setup Info Here...
WiFi.config(ip, dns, gateway, subnet); //If you need Internet Access You should Add DNS also...
WiFi.begin(ssid, password);

But, a few seconds after WiFi.begin is executed the module reboots with an exception 28 and a stack dump.
I tried WiFi.config before and after WiFi.begin. I think that it is triggered by WiFi.config and not by WiFi.begin, it just takes a few seconds until it fails.
All works well with DHCP.
Other thing that's a bit odd is that even with the SSID and password stored in the EEPROM, WiFi.begin() does not work, I'm forced to use WiFi.begin("network", "password"), which of course will waste out the EEPROM as it saves this info every time the module reboots, which is once every minute as it only wakes up to send sensor data to a server and then deep sleeps for 1 minute.

@lrmoreno007

This comment has been minimized.

Copy link
Contributor

@lrmoreno007 lrmoreno007 commented Apr 4, 2017

Your WiFi.config order are bad, must be:
WiFi.config(ip, gateway, subnet, DNS);

Try this:

#include <ESP8266WiFi.h>
IPAddress ip(192, 168, 1, 222);
IPAddress gateway(192, 168, 1, 249);
IPAddress subnet(255, 255, 255, 0);
IPAddress DNS(192, 168, 1, 249);
const char* ssid     = "YOUR_SSID";
const char* password = "your_password";

void setup(){
  Serial.begin(115200);
  WiFi.config(ip, gateway, subnet, DNS);
  delay(100);
  //WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
      Serial.print(".");
      delay(200);
  }
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println();
    Serial.println("Fail connecting");
    delay(5000);
    ESP.restart();
  }
  Serial.print("   OK  ");
  Serial.print("Module IP: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  // put your main code here, to run repeatedly:

}
@vasco65

This comment has been minimized.

Copy link

@vasco65 vasco65 commented Apr 4, 2017

Thanks for the answer lrmoreno007, but as I said above I tried WiFi.config() before AND after WiFi.begin() with the same results. For me it makes more sense to be done BEFORE, but after the 1st reboot I tried all that I could think off.
It looks that the order I'm using in WiFi.config() is wrong, I'm using WiFi.config(myIP, dns, gateway, netmask) and it looks that it should be WiFi.config(myIP, gateway, netmask, dns). But, in any case it should not cause a reboot.

@lrmoreno007

This comment has been minimized.

Copy link
Contributor

@lrmoreno007 lrmoreno007 commented Apr 4, 2017

But, in any case it should not cause a reboot.

Why? For example, a poorly formatted netmask can produce the WDT. The Netmask should be:
255.255.255.0
255.255.0.0
255.0.0.0
Depending on your network configuration. Any other may cause an unexpected error

Have you tried my code?

@vasco65

This comment has been minimized.

Copy link

@vasco65 vasco65 commented Apr 4, 2017

Sorry lrmoreno007, I misread your first line, I thought that you were talking about using WiFi.config before or after Wi.Fi.begin.
I really don't know what to think about this.
I tried your code in an empty sketch and it worked.
Then I pasted your code into my program and put it in a function wifi_init(), this function was the 2nd thing called inside setup(), the 1st was Serial.begin(115200)... And that DID NOT WORK, the exceptions were back.

Then, I took your code to a new sketch and *** slowly *** pasted parts of my program trying it again after almost each line of my code. And now it is working flawlessly, I'm using deepsleep to wait for 1 minute and now it comes back to life in about 2 secs instead of the 5 or 6 it took with DHCP.

I can't thank you enough. You solved it.

But, about the mask, a wrong network mask should not cause nothing more than a host unreachable.
Subnets of class C networks, like /25, /26, 27 are quite common, on my office we have machines in a network with a mask 255.255.128.0. A netmask 192.168.0.1 is not invalid per si, only will not work (unless you know a LOT about networking). But that was not the problem anyway, because that was the 1st thing I tried on my program and it still gave me same errors.

Ok, anyway, it works now, than you very much. 🥇

Unless there is some weird reason saying that WiFi.begin must be called inside of setup() I'm going to bang my head in a table until I found out what's wrong with my code. :-D

@lrmoreno007

This comment has been minimized.

Copy link
Contributor

@lrmoreno007 lrmoreno007 commented Apr 5, 2017

To clarify... It is the WiFi.config declaration order in ESP8266WiFiSTA.cpp

/**
 * Change IP configuration settings disabling the dhcp client
 * @param local_ip   Static ip configuration
 * @param gateway    Static gateway configuration
 * @param subnet     Static Subnet mask
 * @param dns1       Static DNS server 1
 * @param dns2       Static DNS server 2
 */
bool ESP8266WiFiSTAClass::config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2) 

You can init Wifi with a function as you want. This is the template I always use:

#include <ESP8266WiFi.h>
IPAddress ip(10, 0, 1, 15);
IPAddress gateway(10, 0, 2, 200);
IPAddress subnet(255, 0, 0, 0);
IPAddress DNS(10, 0, 2, 1);
const char* ssid     = "XXXXXXX";
const char* password = "YYYYYYY";

void wifi_init(){
  WiFi.config(ip, gateway, subnet, DNS);
  delay(100);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println();
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
      Serial.print(".");
      delay(200);
  }
  Serial.println();
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Fail connecting");
    delay(5000);
    ESP.restart();
  }
  Serial.print("   OK  ");
  Serial.print("Module IP: ");
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  wifi_init();
}

void loop() {
  // put your main code here, to run repeatedly:

}

Regards

@amirusamah

This comment has been minimized.

Copy link

@amirusamah amirusamah commented Oct 10, 2017

hi all. currently i am doing this also. i have done for fixing the ip address. right now, my problem is to connect to vb.
i want to display in the vb what were displayed on the ip address that i fixed it using your coding. in the ip address, i have enter a little bit information. so i need the information in the ip, to display in my vb

very appreciated if you can help

@Tinobrace

This comment has been minimized.

Copy link

@Tinobrace Tinobrace commented Dec 7, 2017

i have been working on this project also and i have been having a little problem obtaining the ip address of my nodemcu. It is always returning 0.0.0.0 as the ip address. How do i alson assign a static ip address to it. I am a noob and am really willing to explore this.

Here's the code

#include <ESP8266WiFi.h>

void setup() {
Serial.begin (9600);
delay(3000);
WiFi.disconnect();
Serial.println("START");
WiFi.begin("AndroidAP");
while ((!WiFi.status() == WL_CONNECTED)){
delay(300);
Serial.print("..");

}Serial.println("Connected!");
Serial.println("Your IP is: ");
Serial.println(WiFi.localIP());
Serial.println("Your gateway is: ");
Serial.println(WiFi.gatewayIP().toString().c_str());
Serial.println("Your host name is:");
Serial.println(WiFi.hostname());

}
void loop() {
}

It is just a simple code yet am having issues with it.

@amirusamah

This comment has been minimized.

Copy link

@amirusamah amirusamah commented Dec 12, 2017

add this code for a static ip
you can assign any of ip by editting IP Address gateway

IPAddress ip(192, 168, 11, 23);
IPAddress gateway(192, 168, 11, 1);
IPAddress subnet(255, 255, 255, 0);
WiFi.config(ip, gateway, subnet);
IPAddress dns(192, 168, 11, 1);
WiFi.config(ip, dns, gateway, subnet);
WiFi.begin(ssid, password)

@nagesh123ee

This comment has been minimized.

Copy link

@nagesh123ee nagesh123ee commented Feb 28, 2018

I am able to set the static ip address with those codes shown above but unable to access the esp web server with the set static ip when connected over the wi-fi network. Please help.

@AJITNAYAK

This comment has been minimized.

Copy link

@AJITNAYAK AJITNAYAK commented Jul 6, 2018

where i can get proper working library #include <ESP8266WiFi.h> . weather this function work with arduino uno and esp8266. in forum it told it work only with NodeMcu V3 board.
Below code work with uno and esp8266 . But how can i assign static ip address

`
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "Twim"; // your network SSID (name)
char pass[] = "12345678"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status

void setup()
{
// initialize serial for debugging
Serial.begin(115200);
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);

// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}

// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}

Serial.println("You're connected to the network");
}

void loop()
{
// print the network connection information every 10 seconds
Serial.println();
printCurrentNet();
printWifiData();

delay(10000);
}

void printWifiData()
{
// print your WiFi shield's IP address
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);

// print your MAC address
byte mac[6];
WiFi.macAddress(mac);
char buf[20];
sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
Serial.print("MAC address: ");
Serial.println(buf);
}

void printCurrentNet()
{
// print the SSID of the network you're attached to
Serial.print("SSID: ");
Serial.println(WiFi.SSID());

// print the MAC address of the router you're attached to
byte bssid[6];
WiFi.BSSID(bssid);
char buf[20];
sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[5], bssid[4], bssid[3], bssid[2], bssid[1], bssid[0]);
Serial.print("BSSID: ");
Serial.println(buf);

// print the received signal strength
long rssi = WiFi.RSSI();
Serial.print("Signal strength (RSSI): ");
Serial.println(rssi);
}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
You can’t perform that action at this time.