Chat freely about anything...

User avatar
By francescobiancardi
#89927 Hello everyone,
I just joined the forum as the owner of several ESP8266 boards of various kinds. I am not an expert and I have the pleasure of understanding and learning to create small projects for myself.

I have a sketch that I have to say does its job. The problem I encounter is related to the connection.
In practice, once the sketch is loaded, the board hooks up to my router. I can see processes via serial monitor.
It happens that, if I restart my Wemos, by pressing the key or by removing the power supply, it can no longer reconnect to the wifi .... I display "Connecting to ....." endlessly from the serial monitor.
Now if I try to reload the sketch it doesn't solve the problem BUT if I load a sketch with a different SSID and then I repeat the procedure by entering the new SSID again, it magically hangs up.
below my sketch that acquires a presence sensor and sends it to home assistant via MQTT..

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "**********";
const char* password = "***********";
const char* mqtt_server = "*************";
#define mqtt_user "mqtt_user"
#define mqtt_password "***************"
#define sensor_topic "sensor\motion1"
int val = 0;
String stringVal = "OFF";

WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to....");
Serial.println(ssid);


WiFi.begin(ssid, password);



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

randomSeed(micros());

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection…");
if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
Serial.println("connected");
client.subscribe("home/alarm/set");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void setup() {
//PIN UTILIZZATO PER IL SENSORE DI MOVIMENTO
pinMode(12, INPUT);


Serial.begin(115200);
Serial.setDebugOutput(true);
setup_wifi();
client.setServer(mqtt_server, 1883);
}

void loop() {

if (!client.connected()) {
reconnect();
}
client.loop();

val = digitalRead(12);
//Serial.println(val);

if (digitalRead(12) == HIGH) {
stringVal = "ON";
Serial.println("Il sensore è stato attivato");
} else {
stringVal = "OFF";
}

client.publish(sensor_topic, String(stringVal).c_str(), true);
delay(1000);

}
Has anyone had the same problem?
User avatar
By Sp0ngeB0b
#90060 hi,i have had similar problems , i traced the issue to the wifi "module" of the SoC taking a bit of time to wake up...
my solution: add "delay(100);" before your wifi setup.it should solve the issue.

you can also try
WiFi.forceSleepWake();