Help with WeMos D1 /ESP8266 connecting to different IP's

Hello there!

So basically I have 2 WeMos D1 r3 boards, which are connected through 2 rooters with server-client connection with a local static IP. Both nodes are far apart(around 2km), but each one has router and cable connects them.

So in the Server, I do the normal connection:

-----------------Server code-----------------------

#include <SPI.h>
#include <ESP8266WiFi.h>

byte ledPin = 2;
char ssid[] = "ssid"; // SSID of your home WiFi
char pass[] = "password"; // password of your home WiFi
unsigned long IntervalIntranet = 120000;
unsigned long PreviousMillis = 0;
String request;

WiFiServer server(80);

IPAddress ip(192, 168, 0, 80); // IP address of the server
IPAddress gateway(192,168,0,1); // gateway of your network
IPAddress subnet(255,255,255,0); // subnet mask of your network

void setup() {
Serial.begin(115200); // only for debug
Serial.println("Connecting...");
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
};
Serial.println("---Connected!---");
Serial.println("Connected to wifi");
Serial.print("Status: "); Serial.println(WiFi.status()); // some parameters from the network
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());
Serial.print("Networks: "); Serial.println(WiFi.scanNetworks());

server.begin();

pinMode(ledPin, OUTPUT);
}

void loop () {

WiFiClient client = server.available();
if (client) {
if (client.connected()) {
digitalWrite(ledPin, LOW); // to show the communication only (inverted logic)
Serial.println(".");
client.print("Hi client! No, I am listening. ");
client.print(analogRead(A0));
client.println("r"); // sends the answer to the client
request = client.readStringUntil('r'); // receives the message from the client
Serial.print("Distance: "); Serial.println(request);
client.flush();
digitalWrite(ledPin, HIGH);
}
client.stop(); // tarminates the connection with the client
};

}

----------END of Server code------------------

On the client-side I have the following code:

--------------Client code begin------------------

#include <SPI.h>
#include <ESP8266WiFi.h>

#define echoPin 12 // Echo Pin D6
#define triggerPin 13 // Trigger Pin D7

long duration, distance;
byte ledPin = 2;
char ssid[] = "ssid"; // SSID of your home WiFi
char pass[] = "password"; // password of your home WiFi

unsigned long askTimer = 0;

IPAddress server(192, 168, 0, 80); // IP address of the server
IPAddress gateway(192,168,0,1); // gateway of your network
IPAddress subnet(255,255,255,0); // subnet mask of your network

WiFiClient client;

void setup() {
Serial.begin(115200); // only for debug
//init the Ultrasonic sensor pins
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
WiFi.mode(WIFI_STA);
WiFi.config(server,gateway,subnet);
WiFi.begin(ssid, pass); // connects to the WiFi router
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
};
//end init Ultrasonic sensor Pins

Serial.println("Connected to wifi");
Serial.print("Status: "); Serial.println(WiFi.status()); // Network parameters
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());

pinMode(ledPin, OUTPUT);

}

void loop () {
client.connect(server, 80); // Connection to the server
digitalWrite(ledPin, LOW); // to show the communication only (inverted logic)
Serial.println(".");
//Section detect the ultrasonic wave
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
Serial.println(distance);
//Delay 50ms before next reading.
delay(50);
//End Section wave detection from the Ultrasonic sensor
//client.print("Hello server! Are you sleeping? ");
client.print(distance); // sends the message to the server
client.println("\r");
String answer = client.readStringUntil('\r'); // receives the answer from the sever
Serial.println("from server: " + answer);
client.flush();
digitalWrite(ledPin, HIGH);
delay(1000); // client will trigger the communication after two seconds

}----------------END client code---------------------

So, I am trying to send data through the Internet(and specifically using Thingspeak) after 10min. It appears so far I was not able to avoid the assigned IP.

The above code works excellent when I do communicate through the predefined routers IP.

Any suggestions/recommendations or solutions are much appreciated.

Thank you in advance!

"Any suggestions/recommendations or solutions are much appreciated."

In the below client code, I don't think that is going to the internet. Maybe use the server URL.

IPAddress server(192, 168, 0, 80); // IP address of the server

Thx for the response.

I did the following in the client code:

---------------Client code

#include <SPI.h>
#include <ESP8266WiFi.h>
#include <ThingSpeak.h>

#define echoPin 12 // Echo Pin D6
#define triggerPin 13 // Trigger Pin D7

long duration, distance;
byte ledPin = 2;
char ssid[] = "ssid"; // SSID of your home WiFi
char pass[] = "password"; // password of your home WiFi

unsigned long IntervalIntranet = 120000;
unsigned long PreviousMillis = 0;
String request;

//---------------- Thingspeak Fill in your credentails ---------------------
unsigned long myChannelNumber = 55555; // Replace the 0 with your channel number
const char * myWriteAPIKey = "apikey"; // Paste your ThingSpeak Write API Key between the quotes

IPAddress server(192, 168, 0, 80); // IP address of the server
IPAddress gateway(192,168,0,1); // gateway of your network
IPAddress subnet(255,255,255,0); // subnet mask of your network

WiFiClient client, client2;

void setup() {
Serial.begin(115200); // only for debug
//init the Ultrasonic sensor pins
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
PreviousMillis = millis();
}

void loop () {
if (millis()<PreviousMillis + IntervalIntranet)
{
//WiFiClient client;
if(WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting...");
WiFi.config(server, gateway, subnet);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
};
Serial.println("---Connected!---");
};
client.connect(server, 80); // Connection to the server
if (client.connected())
{
digitalWrite(ledPin, LOW); // to show the communication only (inverted logic)
Serial.println(".");
//Section detect the ultrasonic wave
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
Serial.println(distance);
//Delay 50ms before next reading.
delay(50);
//End Section wave detection from the Ultrasonic sensor
//client.print("Hello server! Are you sleeping? ");
client.print(distance); // sends the message to the server
client.println("\r");
String answer = client.readStringUntil('\r'); // receives the answer from the sever
Serial.println("from server: " + answer);
client.flush();
digitalWrite(ledPin, HIGH);
delay(1000); // client will trigger the communication after two seconds
};
} else
{
PreviousMillis = millis();
//Disconnect previous WiFi and create new
// WiFiClient client2;
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client2);
//disconnect the previous connection
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
WiFi.forceSleepBegin();
delay(5000);
if(WiFi.status() != WL_CONNECTED){
Serial.print("Attempting to connect to SSID: ");
WiFi.begin(ssid, pass);
while(WiFi.status() != WL_CONNECTED){
Serial.print("> ");
delay(300);
};
Serial.println("\nConnected.");
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());
};
int x = ThingSpeak.writeField(myChannelNumber, 1, distance, myWriteAPIKey);

// Check the return code
if(x == 200){
Serial.println("Channel update successful.");
}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x));
};
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
WiFi.forceSleepBegin();
delay(5000);
};
};

--------------End of client code

It gets attached to the pre-defined IP. It seems I cant erase the connection and initialize it again.

It gets attached to the pre-defined IP. It seems I cant erase the connection and initialize it again.

In the Arduino IDE 'Tools' menu there is an entry labeled 'Erase Flash'. Try changing "Only Sketch" to "Sketch + WiFi Settings". Then upload your code.

Don

floresta:
In the Arduino IDE 'Tools' menu there is an entry labeled 'Erase Flash'. Try changing "Only Sketch" to "Sketch + WiFi Settings". Then upload your code.

Don

Thx for the reply!

I am not sure what an option is that, but it shuts down my computer. I did it twice and the second time went to the hardcore reset.

The 'Erase Flash' option determines what portions of the ESP8266 memory to erase before writing the new program.

By selecting 'Sketch + WiFi Settings' you are telling the IDE to erase not only the old program code but also the information about the last WiFi access point that the ESP8266 used.

I don't see how this menu selection could shut down your computer, but I guess anything is possible. Are you sure you have the correct 'Board' selected in the 'Tools' menu?

Don

I see, but that is not the point, so basically the option you are recommending is irrelevant in my case. My idea is to shut down the Intranet and reconnect to the router again dynamically, but the new connection to allow me to use the Internet. BTW I started the Thingspeak example and all works great.

So the first level is
WiFi.config(ip,gateway,subnet); //Here we establish the IP where the communication will go on
WiFi.begin(ssid,password); //Here we connect to the router

Once I place this in the loop and try to switch, as you can see from the above code. The WiFi.localIP() prints the pre-defined IP channel. It appears

WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
WiFi.forceSleepBegin();

are not erasing the LocalIP variable.

To put your code in a code box, use the </> icon in the far left of the post tool bar and paste your code between the two bracket sets that appear.

To go back and put your code in a code box, in the bottom right of your post, select "more" and click modify. When the modify post opens, high light your code and click the </> in the far left of the post tool bar. This will put you code in code brackets. Then save the changes.

Have you tried to add WiFi.persistent(false) in the sketch after you have selected 'Erase Flash' -> 'Sketch + WiFi Settings' before upload?

I use WiFi.persistent(false) for esp32, but have not yet tested with esp8266.

Like:

void setup() {
 Serial.begin(115200);               // only for debug
 //init the Ultrasonic sensor pins
 pinMode(triggerPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(ledPin, OUTPUT);
 PreviousMillis = millis(); 
 WiFi.persistent(false);            //<--- no save of Wifi setting
}

Once you have loaded the sketch, you do not need to erase Wifi in the 'Erase Flash' option when executing a new upload.

Thx for the reply!

It did not restart my computer this time, but I switched the board option to Wemos D1 R1, and before was LOLIN(Wemos) D1 R2 & mini, plus I added the WiFi.persistent(false);

The unfortunate stuff is, the code is not allowing the IP to be erased

Connecting...
...........---Connected!---
IP: 192.168.0.80
SSID: Dimitar_H
Signal: -77
Attempting to connect to SSID: > > > > > > > > > > >
Connected.
IP: 192.168.0.80
SSID: Dimitar_H
Signal: -71
Problem updating channel. HTTP error code -301
Connecting...
...........---Connected!---
IP: 192.168.0.80
SSID: Dimitar_H
Signal: -64

From reply #5:

By selecting 'Sketch + WiFi Settings' you are telling the IDE to erase not only the old program code but also the information about the last WiFi access point that the ESP8266 used.

This will erase any ssid/password information that the ESP8266 has previously stashed away.

From reply #8:

Have you tried to add WiFi.persistent(false) in the sketch after you have selected 'Erase Flash' -> 'Sketch + WiFi Settings' before upload?
. . .
Once you have loaded the sketch, you do not need to erase Wifi in the 'Erase Flash' option when executing a new upload.

This will prevent the ESP8266 from saving any ssid/password information that your newly programed ESP8266 has used.


I have made no attempt to read your code and will not do so until you follow the procedure given in reply #7 that will put your code in a proper code box.

Your problem, as I perceive it, is that you are telling the ESP8266 to connect using a specific ssid/password combination but it insists on using a previously used (and saved) combination. I believe that (unless instructed otherwise as outlined above) the ESP8266 will save the last combination that it tried to use, even if that attempt was unsuccessful.

If you follow this two step procedure it should solve your problem as I perceive it. Otherwise you should consider restating exactly what problem you are actually having.

Don

Sorry floresta, but I am not accustomed to publishing code or anything online/forums and ask for help. Unfortunately, I need to understand that now.

Client code, or where I am trying to publish the info on the Internet and postponed the broadcasting through the predefined local router IP channel.

#include <ESP8266WiFi.h>
#include <ThingSpeak.h>

#define echoPin 12 // Echo Pin D6
#define triggerPin 13 // Trigger Pin D7

long duration, distance;
byte ledPin = 2;
char ssid[] = "Unknown";           // SSID of your home WiFi
char pass[] = "*****";            // password of your home WiFi

unsigned long IntervalIntranet = 120000;
unsigned long PreviousMillis = 0;
String request;

//----------------  Thingspeak Fill in your credentails   ---------------------
unsigned long myChannelNumber = 55555;  // Replace the 0 with your channel number
const char * myWriteAPIKey = "ThingsSpeak123";    // Paste your ThingSpeak Write API Key between the quotes 


IPAddress server(192, 168, 0, 80);            // IP address of the server
IPAddress gateway(192,168,0,1);           // gateway of your network
IPAddress subnet(255,255,255,0);          // subnet mask of your network

WiFiClient client, client2;

void setup() {
  Serial.begin(115200);               // only for debug
  //init the Ultrasonic sensor pins
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);
  PreviousMillis = millis();  
  WiFi.persistent(false);            //<--- no save of Wifi setting
}

void loop () {
  if (millis()<PreviousMillis + IntervalIntranet)
    { 
    //WiFiClient client;  
    if(WiFi.status() != WL_CONNECTED)
    {
     Serial.println("Connecting...");
     WiFi.config(server, gateway, subnet); 
     WiFi.begin(ssid, pass);
     while (WiFi.status() != WL_CONNECTED) 
      {
        
        Serial.print(".");
        delay(300);
      };
     Serial.println("---Connected!---");  
      Serial.print("IP: ");     Serial.println(WiFi.localIP());
      Serial.print("SSID: "); Serial.println(WiFi.SSID());
      Serial.print("Signal: "); Serial.println(WiFi.RSSI());
    }; 
          client.connect(server, 80);   // Connection to the server
          if (client.connected())
            {
          digitalWrite(ledPin, LOW);    // to show the communication only (inverted logic)
          Serial.println(".");
  //Section detect the ultrasonic wave
          digitalWrite(triggerPin, LOW);
          delayMicroseconds(2);
          digitalWrite(triggerPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(triggerPin, LOW);
          duration = pulseIn(echoPin, HIGH);
    //Calculate the distance (in cm) based on the speed of sound.
          distance = duration/58.2;
          Serial.println(distance);
    //Delay 50ms before next reading.
          delay(50);
  //End Section wave detection from the Ultrasonic sensor
          //client.print("Hello server! Are you sleeping? ");
          client.print(distance);  // sends the message to the server
          client.println("\r");
          String answer = client.readStringUntil('\r');   // receives the answer from the sever
          Serial.println("from server: " + answer);
          client.flush();
          digitalWrite(ledPin, HIGH);
          delay(1000);                  // client will trigger the communication after two seconds
            };
    } else
      { 
        if (client.connected()) client.stop();
        PreviousMillis = millis();
        //Disconnect previous WiFi and create new
     // WiFiClient client2;  
      WiFi.mode(WIFI_STA);
      ThingSpeak.begin(client2);
      //disconnect the previous connection
      WiFi.disconnect(true);
      WiFi.mode(WIFI_OFF);
      WiFi.forceSleepBegin(); //I am not sure if this is necessary
      delay(5000);
      
      if(WiFi.status() != WL_CONNECTED){
        Serial.print("Attempting to connect to SSID: ");
        WiFi.begin(ssid, pass);
        while(WiFi.status() != WL_CONNECTED){
          
            Serial.print("> ");
            delay(300);     
          }; 
      Serial.println("\nConnected.");
      Serial.print("IP: ");     Serial.println(WiFi.localIP());
      Serial.print("SSID: "); Serial.println(WiFi.SSID());
      Serial.print("Signal: "); Serial.println(WiFi.RSSI()); 
      };        
     int x = ThingSpeak.writeField(myChannelNumber, 1, distance, myWriteAPIKey);
  
  // Check the return code
      if(x == 200){
          Serial.println("Channel update successful.");
        }
        else
        {
          Serial.println("Problem updating channel. HTTP error code " + String(x));
          };
           //disconnect again and be ready the for local broadcasting
          WiFi.disconnect(true);
          WiFi.mode(WIFI_OFF);
          delay(5000); 
   };
};

"Client code, or where I am trying to publish the info on the Internet..."

Don't think it is going to happen.

zoomkat:
"Client code, or where I am trying to publish the info on the Internet..."

Don't think it is going to happen.

Why are you so skeptical? Perhaps somebody here might have a solution to that case. I bet many have experienced the need to do those type of communications with the IoT development boards of ESP8266 or ESP32.

"Why are you so skeptical?"

No where in your client code do I see any attempt to connect to the internet.

The section in the ELSE should be about that. I disconnect the current connection and create a new one, which only needs WiFi.begin(ssid,passw) as I understand. Once you do that Internet should be automatically assigned(the router dynamically created IP) by the router. Isnt it?