Setting StaticIP address on ESP8266

thanks guys - so you can setup static IP address and attributes as per your program ONCE then ESP8266 remembers them even if powered off ? With respect to code example,if I have a Wemos then I change serial to RX 1, and 2 respectively ?

if you only using a Wemos i think you should check the manual Ethernet sketch @Lichtsignaal suggested…

got it thanks all :slight_smile:

@mars Yes, the ESP stores the last received setting (e. g. static IP) in its non volatile memory so it remembers even if powerd off. Regarding the serial lines, you can use the most suitable lines for your hardware.
Ciao,
Giancarlo

Hi - I tried to modify the blynk Ethernet sketch for setting static ip for esp8266 but can’t seem to get it to work. Anyone done it successfully without using AT commands ie doing it with blynk.begin api ? If so can you pls share

@mars

#define BLYNK_PRINT Serial    
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h> 

char auth[] = "xxxxxxxxxxxxxxxx";
char ssid[] = "xxxxxxxxxx";
char password[] = "xxxxxxxxxxxx";

IPAddress server_ip (192, 168, 10, 229);

// Mac address should be different for each device in your LAN
byte arduino_mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress arduino_ip ( 192,  168,   10,  20);
IPAddress dns_ip     (  8,   8,   8,   8);
IPAddress gateway_ip ( 192,  168,   10,   90);
IPAddress subnet_mask(255, 255, 255,   0);

void setup()
{
  Serial.begin(115200);
  Serial.println();
  WiFi.config(arduino_ip, gateway_ip, subnet_mask);
  WiFi.begin(ssid, password);
  Blynk.config(auth);
  while (Blynk.connect(1000) == false) { 
  }  
}

void loop()
{
  Blynk.run();
}

thanks Costas - this works, appreciate that.

I assume doing it this way does NOT keep the static IP address within the ESP8266 even when switched off, i.e. I need to setup staticIP eachtime Blynk runs ?
Unlike in the case with using AT commands the ESP8266 remembers the StaticIP settings even when switched off.

Is this correct ?

To be honest I’m not really sure if the IP is saved in none volatile memory like the ssid and pwd. If you are running the sketch then it will always have the same IP when power is restored.

Question on a totally different topic - but I know you understand a lot about given historical posts. I am using the RTC widget in my code and its all compiles fine etc and displays formatted time and date in LCD widget but it always start with time 0.0.0 and date 1.1.1970 - even though I select correct timezone in widget. I am using a local Blynk server and wonder if there is anything special or different I need to do because I am using a local Blynk server ?

It is because the ESP8266 clock hasn’t been sync’d with the server. The default is for the sync to be at 5 minute intervals.

The RTC widget uses this library https://github.com/PaulStoffregen/Time and you can change the sync interval with setSyncInterval( interval), where interval is some seconds.

I have found it doesn’t always sync though if you have a lot of virtualWrite’s and other pin syncing when the ESP boots up.

Extract of a fix below that uses a SimpleTimer every 1 second to try and sync the time, once the time is sync’d the SimpleTimer is deleted.

int clockcounter = 3; // just happens to be our 3rd timer but must be set as an integer to be able to disable the timer

void gettime(){
    if(year() != 1970){  // we have got the right time now so kill the SimpleTimer
      setSyncInterval(300); // normal 5 minute sync interval but not sure this actually works
      timer.deleteTimer(clockcounter);  // don't need this timer anymore
      sprintf(Date, "%02d/%02d/%04d",  day(), month(), year());
      Serial.println(Date);
      sprintf(Time, "%02d:%02d:%02d", hour(), minute(), second());
      Serial.println(Time);
    }
    rtc.begin();  // keep trying to sync the time until year is not 1970
}

void setup(){

clockcounter = timer.setInterval(1000L, gettime); // check if clock has updated every second

}

Edit:
I should have added that you must include the following line in loop()

timer.run(); // plus include required libraries at the top of your sketch

Top of your sketch:

#include <TimeLib.h>
#include <SimpleTimer.h>
SimpleTimer timer;

And a “perfect” loop is:

void loop()
{
  Blynk.run();
  timer.run();  // Costas
}

giving it a try now - been going for 5 mins and still date is 1.1.1970 :frowning:
can it take a long time usually ?

It takes just a few seconds for the sync to take place on our system.

Maybe I should give you a full sketch to try.

Just a thought, is your local server something like a Pi that has been restricted to LAN routing?

hi - i’m running local server on windows 10 pc.
I realized for some reason the interrupt function was not working so I created a little flag checking function which then worked - but then i realized only GMT+11 is available from RTC widget on Blyk App and it should be GMT+10 for Australia/Sydney — I’ve raised another post issue on it earlier.

If you can share the entire script that would be great.

See below: the time in LCD widget is 19:26 which is GMT+11, but the time in the history graph is GMT+10 ! really weird – I don’t know why.

@mars Hi Mars, I report you a note that I wrote in a former post of some days ago:

… the RTC shows 1/1/1970 for the first 5 minutes if you miss this line of code:

while(Blynk.connect() == false);

equivalent to:

while(Blynk.connect() == false)
{
}

This line has to be inserted after Blynk.begin and before rtc.begin:

Blynk.begin(auth, wifi, ssid, pass);

while(Blynk.connect() == false);

rtc.begin();

In such a way the RTC hows immediately the correcet date and time.

Regarding the code to format date and time, in my opinion, the most elegant lines of code are:

sprintf(Date, "%04d/%02d/%02d", year(), month(), day());
sprintf(Time, "%02d:%02d:%02d", hour(), minute(), second());

Blynk.virtualWrite(V1, Date);
Blynk.virtualWrite(V2, Time);

If you don’t want leading zero, exclude the 0 from the formatting section of sprintf.

Date and Time are array of char:

char Date[16];
char Time[16];

Regarding the static IP Address of ESP8266, I have verified that if you assign it with AT commands it is stored in the non volatile memory of ESP.

I hope it could be useful.
Ciao,
Giancarlo

@Costas @Gianca @Dmitriy thanks for your help but I’m finding this rtc not working very well at all wth local blynk server. Is this a know fault / issue. You’ll see when it does connect the time if +1 off but ok in the history graph :frowning:

here is my code (its a work in progress but you can hopefully follow what I’m trying to do) - it works well but clock hardly ever syncs !
perhaps I’m doing something obviously wrong.

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <WidgetRTC.h>
#include <OneWire.h> // make sure used ESP OneWire.h file in ESP folder
#include <DallasTemperature.h>
#include <TimeLib.h>
#include <SimpleTimer.h>

char Date[16];
char Time[16];

#define ONE_WIRE_BUS 13   // GPIO13 = onewire to use PIN 7 on WeMos D1 R2 ESP8266 board
#define TEMPERATURE_PRECISION 12

#define RELAY1  13  // D7
#define RELAY2  12  // D6                       
#define RELAY3  14  // D5
#define RELAY4  4   // D4
                     
DeviceAddress Therm_1 = { 0x28, 0xff, 0x61, 0xd0, 0x64, 0x15, 0x03, 0x5f };
DeviceAddress Therm_2 = { 0x28, 0xFF, 0x2D, 0xD4, 0x64, 0x15, 0x01, 0x25 };
DeviceAddress Therm_3 = { 0x28, 0xFF, 0x18, 0xE7, 0x64, 0x15, 0x01, 0xB3 };
DeviceAddress Therm_4 = { 0x28, 0xFF, 0x70, 0xF4, 0x64, 0x15, 0x02, 0xCE };

DeviceAddress Therm_5 = { 0x28, 0xFF, 0xB0, 0xAB, 0x64, 0x15, 0x01, 0x4C };

int rainSensePin= 0;    // analog pin 0 - sensor  i/p
long BaudRate = 9600, sysTick = 0;
char GotChar;

SimpleTimer timer;

int clockcounter = 3;
bool clock_sync = 0;

WidgetRTC rtc;

BLYNK_ATTACH_WIDGET(rtc, V8);


// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

int numberOfDevices; // Number of temperature devices found

DeviceAddress tempDeviceAddress; // We'll use this variable to store a found device address

// Time to sleep (in seconds):
const int sleepTimeS = 10;
bool V1_written = 0;

char auth[] = "xxxxxxxxx"; // ESP  token for Wemos D1 Project TEMP on LOCAL SERVER";  // Blynk token for ESP8266 Project on LOCAL SERVER


// Mac address should be different for each device in your LAN
byte arduino_mac[] = { xxx, xxx, xxx, xxx ...}
IPAddress arduino_ip ( 192,   168,   0,  253);
IPAddress dns_ip     (  192,   168,   0,   1);
IPAddress gateway_ip ( 192, 168, 0, 1);
IPAddress subnet_mask(255, 255, 255,   0);

void setup()
{
 
  pinMode (13, INPUT_PULLUP); // set GPIO13 Onewire with Internal PULL_UP resistor on for it to work
  
  Serial.begin(9600);
  
  if(oneWire.reset()==1) { Serial.println ("OneWire has been reset correctly");}
  else { Serial.println ("One wire reset was UNSUCCESSFUL!");}

Serial.println("Dallas Temperature IC Control Library Demo");
  // Start up the library
  

  sensors.begin();
  
  
  sensors.setResolution(Therm_1,12);
  sensors.setResolution(Therm_2,12); 
  sensors.setResolution(Therm_3,12); 
  sensors.setResolution(Therm_4,12); 
  sensors.setResolution(Therm_5,12);
   
  // Grab a count of devices on the wire
  numberOfDevices = sensors.getDeviceCount();

  // locate devices on the bus
  Serial.print("Locating devices...");

  Serial.print("Found ");
  Serial.print(numberOfDevices, DEC);
  Serial.println(" devices.");
  Serial.print("Resolution set to:");
  // sensors.setResolution(TEMPERATURE_PRECISION);
  Serial.println(sensors.getResolution());

 
   WiFi.config(arduino_ip, gateway_ip, subnet_mask);
   WiFi.begin("xxxx", "xxxx");
   Blynk.config(auth,IPAddress(xxx,xxx,xxx,xxx));
 
  // Or like this:
  //Blynk.begin(auth, "blynk-cloud.com", 8442, arduino_ip, dns_ip, gateway_ip, subnet_mask, arduino_mac);
  
  while (Blynk.connect() == false) {    // wait for Blynk to be connected
  }  
  rtc.begin();
  Serial.println ("BLYNK is Connected!");

   //  Blynk.syncAll();   // Real all virtualpins   
   //   clockcounter = timer.setInterval (300L, gettime); // check if clock has updated every second
   //Serial.print ("Clockcounter = ");
   // Serial.println (clockcounter);
}

void loop()
{

  // call sensors.requestTemperatures() to issue a global temperature 
  // request to all devices on the bus
  Serial.println("Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");


 // printTemperature(Therm_1, 1);
 // printTemperature(Therm_2, 2);
 // printTemperature(Therm_3, 3);
 // printTemperature(Therm_4, 4);
 printTemperature(Therm_5, 5);
  
  Blynk.run();
   // deepSleep time is defined in microseconds. Multiply
   // seconds by 1e6 
 
   // Serial.println ("I'm going to sleep");
   
     clockDisplay();
     
     if (clock_sync == 0) { gettime();}
          
  //  ESP.deepSleep(sleepTimeS * 1000000); not using this for now
    Serial.println ("I'm awake");
    delay (1000);
  
}


BLYNK_WRITE(V1)
{
 // BLYNK_LOG("Got a value: %s", param.asStr());
  // You can also use:
 int i = param.asInt();
 int state;

 float tempC = sensors.getTempC(Therm_5);
 Serial.print ("Temp C = ");
 Serial.println(tempC);
 Blynk.virtualWrite(V1,tempC);

 V1_written = 1;  // my little flag
}


 
bool isFirstConnect = true;

BLYNK_CONNECTED() {
  if (isFirstConnect) {
  //  Blynk.syncAll();   // not doing much for now
    isFirstConnect = false;
    Serial.println ("Blynk First connected EXECUTED");   
  }
 
}


// function to print the temperature for a device to Blynk app
void printTemperature(DeviceAddress deviceAddress, int thermostat_label)
{
  // method 1 - slower
  //Serial.print("Temp C: ");
  //Serial.print(sensors.getTempC(deviceAddress));
  //Serial.print(" Temp F: ");
  //Serial.print(sensors.getTempF(deviceAddress)); // Makes a second call to getTempC and then converts to Fahrenheit

  // method 2 - faster
  float tempC = sensors.getTempC(deviceAddress);
  
  Serial.print("Thermostat : ");
  Serial.println(thermostat_label);
  Serial.print("Temp C: ");
  Serial.print(tempC);
  Serial.print(" Temp F: ");
  Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
  Serial.println("...temperatere read ok..... pls wait");
  Serial.println(" ");

  Blynk.virtualWrite(V1,tempC);
}


// Digital clock display of the time in Blynk App

void clockDisplay()
{
  // You can call hour(), minute(), ... at any time
  // Please see Time library examples for details

 
  sprintf(Date, "%02d/%02d/%04d",  day(), month(), year());
  sprintf(Time, "%02d:%02d:%02d", hour(), minute(), second());
  Serial.print("Current time: ");
  Serial.print(Time);
  Serial.print(" ");
  Serial.print(Date);
  Serial.println();

  // Send time to the App
  Blynk.virtualWrite(V2, Time);
  // Send date to the App
  Blynk.virtualWrite(V3, Date);
}


void gettime(){
    Serial.print ("Year in gettime = ");
    Serial.println (year());
    if(year() != 1970){  // we have got the right time now so kill the SimpleTimer
      setSyncInterval(300); // normal 5 minute sync interval but not sure this actually works
   //   timer.deleteTimer(clockcounter);  // don't need this timer anymore
     sprintf(Date, "%02d/%02d/%04d",  day(), month(), year());
      Serial.println(Date);
     sprintf(Time, "%02d:%02d:%02d", hour(), minute(), second());
     Serial.println(Time);
     clock_sync = 1;         // set clock_sync flag to TRUE so we don't call gettime function again from void loop ()
    }
    else {
      Serial.println ("still trying to sync :-(");
      rtc.begin();  // keep trying to sync the time until year is not 1970
    }         
 }

@mars the sketch by @Gianca will not work if you have a project where you have a lot of sync and virtualWrite entries in setup(). Either it will sync the time and skip the other syncs and virtualWrite’s or it will skip the time sync and do the other stuff.

Below are a couple of extracts from Serial Monitor. The first is with line 11 of the following sketch commented out (so without a fixed IP for the ESP) and the second is with a fixed IP for the ESP (line 11 not commented out).

Attempting to connect to SSID: MTN WIFI 19996
[260] Connecting to MTN WIFI 19996
[2261] Connected to WiFi
[2261] IP: 192.168.10.156
[2261] Blynk v0.3.8 on ESP8266
WiFi connected with IP address: 192.168.10.156
[5001] Connecting to blynk-cloud.com:8442
[5137] Ready (ping: 0ms).
Connected to Server
[6275] Time sync: OK
Date is: 04/09/2016 and the time is now 12:45:09
[7277] Time sync: OK




Attempting to connect to SSID: MTN WIFI 19996
.
[761] Blynk v0.3.8 on ESP8266
WiFi connected with IP address: 192.168.10.20
[5001] Connecting to blynk-cloud.com:8442
[5152] Ready (ping: 1ms).
Connected to Server
[6291] Time sync: OK
Date is: 04/09/2016 and the time is now 12:48:46
[7292] Time sync: OK

Look through this sketch, change the settings but nothing else and let me know what you get.

// ESP_RTC_FixedIP.ino by Costas 4th Sept 2016
//http://community.blynk.cc/t/setting-staticip-address-on-esp8266/7866

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <TimeLib.h>
#include <WidgetRTC.h>

#define FIXEDIP // comment this out if you don't want to assign a fixed IP to the ESP

#ifdef FIXEDIP
  // Configure your own IP details in this section *********************
  IPAddress server_ip (192, 168, 10, 229);
  // Mac address should be different for each device in your LAN
  byte arduino_mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
  IPAddress arduino_ip ( 192,  168,   10,  20);
  IPAddress dns_ip     (  8,   8,   8,   8);
  IPAddress gateway_ip ( 192,  168,   10,   90);
  IPAddress subnet_mask(255, 255, 255,   0);
  // end of static IP configuration for ESP ***************************
#endif

SimpleTimer timer;
WidgetRTC rtc;
BLYNK_ATTACH_WIDGET(rtc, V24);  // change to you chosen virtual pin
char Date[16];
char Time[16];
char ssid[] = "MTN WIFI 19996";
char pass[] = "xxxxxxxxxx";
char auth[] = "xxxxxxxxxxxxxxxxxxx";
int clockcounter = 3;

char connectionStatus[28] = "Connected to Server"; // default is that a connection will be made to the server

void gettime(){
    if(year() != 1970){  // we have got the right time now, so kill the SimpleTimer
      setSyncInterval(300); // normal 5 minute sync interval but not sure this actually works
      timer.deleteTimer(clockcounter);  // don't need this timer anymore, kill it
      sprintf(Date, "%02d/%02d/%04d",  day(), month(), year());
      sprintf(Time, "%02d:%02d:%02d", hour(), minute(), second());
      Serial.print("Date is: ");
      Serial.print(Date);
      Serial.print(" and the time is now ");
      Serial.println(Time);
    }
    rtc.begin();  // keep trying to sync the time until year is not 1970
}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);
  
  #ifdef FIXEDIP
    //**************** this section is to allocate fixed IP to ESP ***************************
      WiFi.config(arduino_ip, gateway_ip, subnet_mask);
      WiFi.begin(ssid, pass);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      } 
      Serial.println(); 
      Blynk.config(auth);
    //*************** end of fixed IP allocation section *************************************/
  #else
    Blynk.begin(auth, ssid, pass);  // Fixed IP is not required for the ESP
  #endif
  
  Serial.print("WiFi connected with IP address: ");
  Serial.println(WiFi.localIP());
    
  int mytimeout = millis() / 1000;
  while (Blynk.connect(7000) == false) { // try to connect to server for 7 seconds
    if((millis() / 1000) > mytimeout + 4){ // continue if not connected within 5 seconds
      strcpy(connectionStatus, "Failed to connect to server");
      break;
    }
  }  
  Serial.println(connectionStatus);
  clockcounter = timer.setInterval(1000L, gettime); // check every second if clock has updated then delete this timer
}

void loop()
{
  Blynk.run();
  timer.run();
}

Meanwhile I will take a quick look at your sketch.

@mars I have done a few mods to your sketch and below is the Serial Monitor output when connecting to a Pi Zero.

Dallas Temperature IC Control Library Demo
Locating devices...Found 0 devices.
Resolution set to:9
.
[775] Blynk v0.3.8 on ESP8266
[5001] Connecting to 192.168.10.229:8442
[5105] Ready (ping: 7ms).
Blynk First connected EXECUTED
BLYNK is Connected!
Requesting temperatures...
DONE
Thermostat : 5
Temp C: -127.00 Temp F: -196.60
...temperature read ok..... pls wait
 
Current time: 00:00:05 01/01/1970
Year in gettime = 1970
still trying to sync :-(
I'm awake
Requesting temperatures...
DONE
Thermostat : 5
Temp C: -127.00 Temp F: -196.60
...temperature read ok..... pls wait
 
[6442] Time sync: OK
Year in gettime = 2016
04/09/2016
13:55:42
Current time: 13:55:42 04/09/2016
I'm awake
Requesting temperatures...
DONE
Thermostat : 5
Temp C: -127.00 Temp F: -196.60
...temperature read ok..... pls wait

I haven’t hooked up a temperature sensor so it defaults to -127.00 but as you will see it takes 5 seconds to connect and within a further 1.5 seconds it has the correct time.

You loop() is a real mess. You shouldn’t be trying to read the temperature and time a thousand times a second. That is what a loop() does. I can see your deepsleep entries are commented out at the moment and you could argue when enabled the bad loop will not be important. This is not true because it is simply bad practise not to use SimpleTimer for your functions.

That is one reason you have had problems with RTC, the loop is so busy that RTC function can’t be called. I’ll post your amended sketch shortly.

thanks for initial feedback - I’m trying your sketch now.

BTW: given i have a delay (1000) in my main loop does that not reduce the amount of time the loop is run to ONCE per second ?

Yes it does but that is not the way to do it.
What time is it with you?

Edit:

What you were doing with delay(1000) in the loop and rtc.begin() in setup() was:

Asking for the time
Going off to the loop() working hard then waiting, followed by working hard then waiting etc and it never gets the chance to actually recheck the time on the server. Must be 1 second timer as then there is no waiting involved.