I would appreciate some education regarding this matter. I have project with the code shown that will be used to run a handheld remote control for controlling a sonoff basic switch. With some help from others on this forum I got the software working but have now run into another issue that I am not sure what to blame it on, hardware or software. I have the same issue when using either of these two devices. An ESP8266-12E NodeMCU or a Wemos D1 mini pro. The issue is the same on either device. The sketch compiles and uploads with no issues. The serial monitor reports connected to wifi and MQTT. And when pushing the button, everything works fine on and off for both the onboard LED and the remote sonoff switch. BUT after 30~ seconds of NO button activity, system goes dead. Pushing the button will change the LED state but the MQTT message is not being sent and of course the remote switch does not work. I have verified that the MQTT messages are not there using MQTTLens app. Simply pushing the reset button on the associated esp device brings operation back, but only if you start pushing the button right away.
Any and all assistance greatly appreciated. I am extremely new to this...
KentM
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "xx";
const char* password = "xxx";
const char* mqttServer = "192.168.1.x";
const int mqttPort = 1883;
#define LED 5 // D1(gpio5)
#define BUTTON 4 //D2(gpio4)
//Let's say you have your push button on pin 4
int switchState = 0; // actual read value from pin4
int oldSwitchState = 0; // last read value from pin4
int lightsOn = 0; // is the switch on = 1 or off = 0
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("Connecting to WiFi..");
Serial.println("Connected to ");
Serial.print(ssid);
}
client.setServer(mqttServer, mqttPort);
// client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client" )) {
Serial.print("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish("home/office/sonoff1", "Remote");
client.subscribe("home/office/sonoff1");
pinMode(BUTTON, INPUT); // push button
pinMode(LED, OUTPUT); // anything you want to control using a switch e.g. a Led
}
void loop ()
{
switchState = digitalRead(BUTTON); // read the pushButton State
if (switchState != oldSwitchState) // catch change
{
oldSwitchState = switchState;
if (switchState == HIGH)
{
// toggle
lightsOn = !lightsOn;
}
if(lightsOn)
{
digitalWrite(LED, HIGH); // set the LED on
client.publish("home/office/sonoff1", "on");
}
else
{
digitalWrite(LED, LOW); // set the LED off
client.publish("home/office/sonoff1", "off");
}
}
}