I am using a very lightly modified version of the sketch in the Sparkfun Thing MQTT tutorial. The only modification is to remove the switch stuff (at the moment, I’m just trying to get it to connect to the wifi network), and to switch on an LED at boot, so that I can easily see restarts (but this issue happened even before I made this modification). Also, this line char ssid[] = "foo";
was modified to prevent a compilation failure.
Code:
/******************************************************************************
MQTT_Switch_Example.ino
Example for controlling a light using an MQTT switch
by: Alex Wende, SparkFun Electronics
This sketch connects the ESP32 to a MQTT broker and subcribes to the topic
room/light. When the button is pressed, the client will toggle between
publishing "on" and "off".
******************************************************************************/
#include <WiFi.h>
#include <PubSubClient.h>
#define ESP8266_LED 5
char ssid[] = "foo"; // name of your WiFi network
const char *password = "bar"; // password of the WiFi network
const char *ID = "Example_Switch"; // Name of our device, must be unique
const char *TOPIC = "room/light"; // Topic to subcribe to
IPAddress broker(192,168,1,142); // IP address of your MQTT broker eg. 192.168.1.50
WiFiClient wclient;
PubSubClient client(wclient); // Setup MQTT client
bool state=0;
// Connect to WiFi network
void setup_wifi() {
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password); // Connect to network
while (WiFi.status() != WL_CONNECTED) { // Wait for connection
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
// Reconnect to client
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(ID)) {
Serial.println("connected");
Serial.print("Publishing to: ");
Serial.println(TOPIC);
Serial.println('\n');
} else {
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(ESP8266_LED, OUTPUT);
digitalWrite(ESP8266_LED, HIGH);
Serial.begin(115200); // Start serial communication at 115200 baud
delay(100);
setup_wifi(); // Connect to network
client.setServer(broker, 1883);
}
void loop() {
if (!client.connected()) // Reconnect if connection is lost
{
reconnect();
}
client.loop();
}
Serial output:
Connecting to foo
ets Jan 8 2013,rst cause:4, boot mode:(3,6)
wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld
The above repeats every five seconds or so. It seems that this is caused by the watchdog timer, but I’m not sure how to fix it.