I would like to use ESP-01 module and Arduino UNO in order to connect to a WiFi network and connect to a public MQTT broker. However, my code does not work.
#include <SoftwareSerial.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <PubSubClient.h> // The MQTT library
SoftwareSerial espSerial = SoftwareSerial(2,3);
const char* ssid = "xxx";
const char* password = "xxx";
// Public MQTT broker
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port =1883;
const int websocket_port=8000;
WiFiEspClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(9600);
espSerial.begin(9600);
espSerial.setTimeout(50);
connectToWiFiNetwork();
//connect to MQTT server
client.setServer(mqtt_server, mqtt_port);
//client.setCallback(callback);
randomSeed(micros());
String clientId = "xxx-"; // Create a random client ID
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
}
else {
Serial.print("\nfailed, rc=");
Serial.println(client.state());
}
}
void connectToWiFiNetwork(){
Serial.println("Connecting to "+String(ssid));
while (espSerial.available()) espSerial.read();
espSerial.println("AT+GMR"); // print firmware info
waitForResponse("OK",1000);
espSerial.println("AT+CWMODE=1"); // configure as client
waitForResponse("OK",2000);
espSerial.print("AT+CWJAP=\""); // connect to your WiFi network
espSerial.print(ssid);
espSerial.print("\",\"");
espSerial.print(password);
espSerial.println("\"");
waitForResponse("OK",10000);
}
boolean waitForResponse(String target1, int timeout){
String data="";
char a;
unsigned long startTime = millis();
boolean rValue=false;
while (millis() - startTime < timeout) {
while(espSerial.available() > 0) {
a = espSerial.read();
/*if (debug)*/ Serial.print(a);
if(a == '\0') continue;
data += a;
}
if (data.indexOf(target1) != -1) {
rValue=true;
break;
}
}
return rValue;
}
ESP-01 connects to WiFi correctly, however when it reaches the point when it has to connect to MQTT broker, the Serial monitor just give me some stupid characters. What should I do? Could you recommend a solution for it?