I want to configure ESP in smart mode If I press the button for 10 seconds, and then connect to the MQTT broker to send / rec messages and the wifi user and password are saved in esp for next turn on, but my code does not work, Is there a library? Or an example to do this?
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
#include <Thread.h>
const char* mqttServer = "gw.zmd-par.com"; //
const int mqttPort = 1883;
Thread myThread = Thread();
WiFiUDP Udp;
WiFiClient espClient;
PubSubClient client(espClient);
#define pin 12
int cnt = 0;
int count = 0;
int sensorVal;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(pin,INPUT);
Serial.println("here");
myThread.onRun(try1);
myThread.setInterval(200);
}
void loop() {
client.loop();
sensorVal = digitalRead(pin);
// Serial.println(sensorVal);
if (sensorVal == HIGH){
cnt ++ ;
// Serial.println(cnt);
if(cnt == 10){
Serial.println("wifi reset");
wifiReset();
cnt=0;
}
}
if (sensorVal == LOW)
cnt =0;
// }
//print out the value of the pushbutton
delay(1000);
// Serial.println(sensorVal);
}
void wifiReset(){
WiFi.disconnect(true); // remove wifi details stored already
cnt=0;
WiFi.mode(WIFI_STA);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
if(count++ >= 10){
WiFi.beginSmartConfig();
while(1){
delay(1000);
if(WiFi.smartConfigDone()){
Serial.println("SmartConfig Success");
break;
}
}
}
}
Serial.println("");
Serial.println("");
WiFi.printDiag(Serial);
// Start the server
Udp.begin(49999);
Serial.println("USP Server started");
// Print the IP address
Serial.println(WiFi.localIP());
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void try1(){
// Check if a client has connected
Udp.parsePacket();
while(Udp.available()){
Serial.println(Udp.remoteIP());
Udp.flush();
cnt=0;
delay(5);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client" )) {
Serial.println("connected");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}