The ESP8266 is not connecting to MQTT broker hivemq - mqtt

I have a simple code in which I am trying to connect to HiveMQ open broker and subscribe to a topic to listen to incoming messages.
here is the code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char *ssid = "P9Inct"; // cannot be longer than 32 characters!
const char *pass = "P9inct123*"; //
const char *mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char *mqtt_user = "testUser";
const char *mqtt_pass = "abc123";
const char *mqtt_client_name = "12312312332212";
#define BUFFER_SIZE 100
String incoming="";
String did="";
String state="";
// Update these with values suitable for your network.
//IPAddress server(172, 16, 0, 2);
String DEVID="8581870006";//"6931108641";//old
WiFiClient wclient;
PubSubClient client(wclient, mqtt_server,mqtt_port);
void callback(const MQTT::Publish& pub) {
// handle message arrived
Serial.print(pub.topic());
Serial.print(" => ");
if (pub.has_stream()) {
uint8_t buf[BUFFER_SIZE];
int read;
while (read = pub.payload_stream()->read(buf, BUFFER_SIZE)) {
Serial.write(buf, read);
}
pub.payload_stream()->stop();
Serial.println("");
} else
Serial.println(pub.payload_string());
////////////////////////////////////////////
incoming=String(pub.payload_string());
Serial.println(pub.payload_string());
Serial.println(incoming);
}
void setup() {
// Setup console
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED)
return;
Serial.println("WiFi connected");
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
Serial.println("Connecting to MQTT server");
if (client.connect(MQTT::Connect(mqtt_client_name)
.set_auth(mqtt_user, mqtt_pass))) {
Serial.println("Connected to MQTT server");
client.set_callback(callback);
client.subscribe("diy/1"+DEVID);
} else {
Serial.println("Could not connect to MQTT server");
}
}
if (client.connected())
client.loop();
}
}
WiFi connection is working fine but, communication via broker is not working and it always gives the message "Could not connect to MQTT server". How to make esp8266 work with HiveMQ broker. The dashboard of borker is
http://www.mqtt-dashboard.com/

So, you are connected. You have unnecessary print line in your loop. Try to adapt on this :
/* Incoming data callback. */
void callback(char* topic, byte* payload, unsigned int length)
{
char payloadStr[length + 1];
memset(payloadStr, 0, length + 1);
strncpy(payloadStr, (char*)payload, length);
Serial.printf("Topic : [%s]\n", topic);
Serial.printf("Payload : %s\n", payloadStr);
}
void performConnect()
{
uint16_t connectionDelay = 5000;
while (!client.connected())
{
if (client.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_KEY))
{
Serial.printf("Connected to Broker.\n");
client.subscribe("diy/1"+DEVID);
}
else
{
Serial.printf("MQTT Connect failed, rc = %d\n", client.state());
Serial.printf("Trying again in %d msec.\n", connectionDelay);
delay(connectionDelay);
}
}
}
void loop()
{
if (!client.connected())
{
performConnect();
}
client.loop();
}

Related

ESP8266 WIFI single relay ESP-12F Dev board

I am beginner. I am using ESP8266 WIFI single relay ESP-12F Dev board to send some data over MQTT with PubSub client, it used to work well but after sometime(1-2 days) it does not receive message through MQTT. When I reset the board, it get starts working. I do not where the issue is and where is it freezing.
I am storing MQTT credentials in EEPROM also.
Here's my code
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <PubSubClient.h>
#include <WiFiManager.h>
#include <EEPROM.h>
WiFiClient espClient;
PubSubClient client(espClient);
const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>
<h3> HTML Form ESP8266</h3>
<form action="/action_page">
Topic name:<br>
<input type="text" name="PublishTopic" value="">
<br>
Broker name:<br>
<input type="text" name="Mqtt_Broker" value="">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
)=====";
//SSID and Password of your WiFi router
const char* ssid = "Cherry"; //Daalchini#2.4Ghz
const char* password = "ravan#123"; //G_2425G_A
ESP8266WebServer server(80); //Server on port 80
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s); //Send web page
}
//===============================================================
// This routine is executed when you press submit
//===============================================================
void handleForm() {
String PublishTopic = server.arg("PublishTopic");
String Mqtt_Broker = server.arg("Mqtt_Broker");
const char* topic = PublishTopic.c_str(); //strstr( PublishTopic.c_str(), "]" );
const char* mqtt_server = Mqtt_Broker.c_str();
Serial.print("topic:");
Serial.println(topic);
Serial.print("PublishTopic:");
Serial.println(PublishTopic);
Serial.print("mqtt_server:");
Serial.println(mqtt_server);
Serial.print("MQTT Broker:");
Serial.println(Mqtt_Broker);
if(mqtt_server)
{
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
reconnect(topic);
if(!client.connected())
{
reconnect(topic);
Serial.print("disconnected");
}
}
String s = "<a href='/'> Go Back </a>";
server.send(200, "text/html", s); //Send web page
// Writing
int str1AddrOffset = writeStringToEEPROM(0,topic);
int str2AddrOffset = writeStringToEEPROM(str1AddrOffset,mqtt_server);
}
//==============================================================
// SETUP
//==============================================================
//===========================================
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived : ");
Serial.print(topic);
Serial.print(" : ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
}
//===========================================
void reconnect(const char* topic)
{
while(!client.connected()){
Serial.println("Attempting MQTT connection");
if(client.connect(""))
{
Serial.println("Connected");
//client.publish("justinmqtt/house/TMP","Connected!");
client.subscribe(topic);
Serial.print("subscribed!");
}
else
{
Serial.print("Failed, rc = ");
Serial.print(client.state());
Serial.println("Waiting for 5 seconds to try again");
delay(5000);
}
}
}
void setup(void){
Serial.begin(9600);
EEPROM.begin(512);
WiFi.begin(ssid, password); //Connect to your WiFi router
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println("WiFi");
String newStr1;
String newStr2;
int readstr = readingData(0, &newStr1);
int readstr1 = readingData(readstr, &newStr2);
const char* top = newStr1.c_str(); //strstr( PublishTopic.c_str(), "]" );
const char* servermqtt = newStr2.c_str();
Serial.println("top");
Serial.println(top);
Serial.println("servermqtt");
Serial.println(servermqtt);
if(servermqtt)
{
Serial.print("entering in a loop: ");
client.setServer(servermqtt, 1883);
client.setCallback(callback);
reconnect(top);
if(!client.connected())
{
reconnect(top);
Serial.print("disconnected");
}
}
else{
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
server.on("/", handleRoot); //Which routine to handle at root location
server.on("/action_page", handleForm); //form action is handled here
server.begin(); //Start server
Serial.println("HTTP server started");
}
// Serial.print("IP address: ");
// Serial.println(WiFi.localIP()); //IP address assigned to your ESP
//
// server.on("/", handleRoot); //Which routine to handle at root location
// server.on("/action_page", handleForm); //form action is handled here
//
// server.begin(); //Start server
// Serial.println("HTTP server started");
}
//==============================================================
// WRITE EEPROM
//==============================================================
int writeStringToEEPROM(int addrOffset, const String &strToWrite)
{
Serial.println("Writing Data ");
byte len = strToWrite.length();
Serial.println(len);
EEPROM.write(addrOffset, len);
for (int i = 0; i < len; i++)
{
EEPROM.write(addrOffset + 1 + i, strToWrite[i]);
}
EEPROM.commit();
return addrOffset + 1 + len;
}
//==============================================================
// READ EEPROM
//==============================================================
int readingData(int addrOffset, String *strToRead)
{
Serial.println("Reading Data");
int newStrLen = EEPROM.read(addrOffset);
char data[newStrLen + 1];
for (int i = 0; i< newStrLen; i++) {
data[i] = EEPROM.read(addrOffset + 1 + i);
}
data[newStrLen] = '\0';
Serial.println(data);
*strToRead = String(data);
return addrOffset + 1 + newStrLen;
}
//==============================================================
// LOOP
//==============================================================
void loop(void){
server.handleClient(); //Handle client requests
yield();
delay(50);
client.loop();
}

ESP8266 - Setting Wifi Credentials programmatically and then checking they are valid, and then change them if they are not (without reset)

I have an NodeMCU chip that needs to connect to my home wifi and post an http request. I use the chip in WIFI_STA_AP mode as I need the chip to both accept requests via http and issue requests by http.
I do not want to hard-code my home's SSID/Password into the chip, so I have written some code that places the ESP (NodeMCU) into AP mode, receives the SSID/Pass via an http request and saves it on EEPROM.
This works great.
In the code below, onTestWifi() is called when I call http://192.168.4.1/test_wifi?wifi_ssid=mySsid&wifi_password=myPassword. The ssid and password are provided to the WiFi.begin() function. However, if I accidentally type in the wrong password and use it in WiFi.begin(), the connection will always fail until reset the chip and then insert the correct password.
What am I missing? Is it possible to change the ESP's wifi credentials programmatically, without having to reset the chip? Resetting the chip causes the client (in the case, an iPhone app) to disconnect from the chip and this breaks the entire program flow.
Here's the experimentation code I am using:
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
yield();
}
void loop() {
server.handleClient();
}```
OK, so I figured it out. Had to add the line WiFi.disconnect(true) in the onTestWifi() function. Apparently it disconnects from the network and erases the credentials. This stuff is very poorly documented and I wasted days on it.
I hope someone finds it useful.
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
ESP8266WebServer server(80);
ESP8266WiFiMulti WiFiMulti;
void setup() {
Serial.begin(115200);
Serial.println("");
delay(100);
Serial.println("Starting...");
WiFi.persistent(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("APSSID");
IPAddress ip = WiFi.softAPIP();
server.on("/test_wifi", onTestWifi);
server.begin();
yield();
}
void onTestWifi()
{
char ssid[30] = "";
char password[30] = "";
for (int i = 0; i < server.args(); i++)
{
String n = server.argName(i);
String v = server.arg(i);
if (n == "wifi_ssid")
v.toCharArray(ssid, 30);
else if (n == "wifi_password")
v.toCharArray(password, 30);
yield();
}
Serial.print("Connecting to: ");
Serial.print(ssid);
Serial.print(" ");
Serial.println(password);
delay(100);
WiFi.begin(ssid, password);
yield();
int counter = 0;
while (WiFi.status() != WL_CONNECTED && counter < 10)
{ // Wait for the Wi-Fi to connect
delay(1000);
Serial.print(++counter);
Serial.print(' ');
}
if (WiFi.status() != WL_CONNECTED)
{ // Failed to connect.
Serial.println("Connection failed!");
}
else {
Serial.println("Connection succeeded!");
}
WiFi.disconnect(true); // <--- Added this line
yield();
}
void loop() {
server.handleClient();
}

MQTT subscription

Can someone help me with this code?
The goal is to trigger a Led when the value of the payload is > 1000.
It is a MQTT subscribtion code based on the esp8266mqtt PubSub client example. I will use it for a subscribyion of a topic from a CO2sensor
I've tried to modify a part of it but I think it has yo do something with the kind of datatype or a wrong condition?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char *ssid = "xxx";
const char *password = "xxx";
const char *mqtt_server = "xxxx";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int led = D4;
void setup_wifi()
{
delay(10);
// We start by connecting to a WiFi network
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 callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the LED if value of C02 is above 1000
i = atoi (payload); //convert string to integer
if ( i > 1000) // comparison
{
digitalWrite(led, HIGH); // Turn the LED on
}
else
{
digitalWrite(led, LOW); // Turn the LED off
}
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "Test");
// ... and resubscribe
client.subscribe("my/sensors/co2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
pinMode(led, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
if (!client.connected())
{
reconnect();
}
client.loop();
}
Kind regards
Hi, This is what I publish:
void pubMessage() {
char message[16];
snprintf(message, sizeof(message), "%d", co2);
client.publish("my/sensors/co2", message);
delay(30000);
First you are casting the first byte of payload to a char.
Since it's just the first byte, it has a max value of 256.
Second you are comparing that 1 bytes value to the string '1000'
Without knowing exactly what you are publishing it is very hard to tell you how to fix it.
If you are publishing a string representing the number then you will need to parse it first with atoi() then do the comparison to the integer 1000 not the string.
If it is a byte value then you will need to read the correct value from the incoming byte array before doing the comparison.

I am writing a code to read DHT11 value and control 4 relay but temp. sensor is showing me "nan" everytime

I am making a project on home automation with temperature reading using NodeMCU (ESP8266-12E). I am using a DHT11 sensor with DHT11.h library, but my temperature sensor is showing me "nan" instead of any value. I don't know where I am lagging.
My code is given below:
#include "DHT.h" // including the library of DHT11 temperature and humidity sensor
#define DHTTYPE DHT11 // DHT 11
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define Relay1 D1
#define Relay2 D2
#define Relay3 D3
#define Relay4 D4
#define DHTPIN D0
DHT dht(DHTPIN, DHTTYPE);
float temp_f;
String webString = "";
unsigned long previousMillis = 0;
const long interval = 2300;
#define WLAN_SSID "internet" // Your SSID
#define WLAN_PASS "*********" // Your password
/************************* Adafruit.io Setup *********************************/
#define AIO_SERVER "io.adafruit.com" //Adafruit Server
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "foo" // Username
#define AIO_KEY "bar" // Auth Key
//WIFI CLIENT
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
const char TEMP_FEED[] PROGMEM = AIO_USERNAME "/feeds/photocell";
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME"/feeds/photocell");
Adafruit_MQTT_Subscribe Light1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay1"); // Feeds name should be same everywhere
Adafruit_MQTT_Subscribe Light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay2");
Adafruit_MQTT_Subscribe Light3 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay3");
Adafruit_MQTT_Subscribe Light4 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/Relay4");
void MQTT_connect();
void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();
// Print temperature sensor details.
pinMode(Relay1, OUTPUT);
pinMode(Relay2, OUTPUT);
pinMode(Relay3, OUTPUT);
pinMode(Relay4, OUTPUT);
// Connect to WiFi access point.
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
temp_f = dht.readTemperature(true);
Serial.println();
Serial.print("Initial Temp: ");
Serial.println(temp_f);
Serial.println();
mqtt.subscribe(&Light1);
mqtt.subscribe(&Light3);
mqtt.subscribe(&Light2);
mqtt.subscribe(&Light4);
}
int delayTime = 300000; //Wait 5 minutes before sending data to web
int startDelay = 0;
void loop()
{
MQTT_connect();
if (millis() - startDelay < delayTime) {
Serial.println("waiting delaytime");
}
else {
temp_f = dht.readTemperature(true); //Get temp in Farenheit
startDelay = millis();
Serial.print(F("\nSending temp: "));
Serial.print(temp_f);
Serial.print("...");
if (!photocell.publish(temp_f)) { //Publish to Adafruit
Serial.println(F("Failed"));
}
else {
Serial.println(F("Sent!"));
}
}
/* //int t = dht.readTemperature(true);
// t = t/100000000;
Serial.print(F("\nSending photocell val "));
Serial.print(t);
Serial.print("...");
if (! photocell.publish(t)) {
Serial.println(F("Failed"));
} else {
Serial.println(F("OK!"));
}*/
Adafruit_MQTT_Subscribe* subscription;
while ((subscription = mqtt.readSubscription(2000))) {
if (subscription == &Light1) {
Serial.print(F("Got: "));
Serial.println((char*)Light1.lastread);
int Light1_State = atoi((char*)Light1.lastread);
digitalWrite(Relay1, Light1_State);
}
if (subscription == &Light2) {
Serial.print(F("Got: "));
Serial.println((char*)Light2.lastread);
int Light2_State = atoi((char*)Light2.lastread);
digitalWrite(Relay2, Light2_State);
}
if (subscription == &Light3) {
Serial.print(F("Got: "));
Serial.println((char*)Light3.lastread);
int Light3_State = atoi((char*)Light3.lastread);
digitalWrite(Relay3, Light3_State);
}
if (subscription == &Light4) {
Serial.print(F("Got: "));
Serial.println((char*)Light4.lastread);
int Light4_State = atoi((char*)Light4.lastread);
digitalWrite(Relay4, Light4_State);
}
}
// this is our 'wait for incoming subscription packets and callback em' busy subloop
// try to spend your time here:
mqtt.processPackets(500);
}
void MQTT_connect()
{
int8_t ret;
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) {
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000);
retries--;
if (retries == 0) {
while (1);
}
}
Serial.println("MQTT Connected!");
}
you try to read temperature and humidity in setup(). but you need to wait 2s at minima after the dht.begin and before reading, because Sensor readings may also be up to 2 seconds
so add delay(2000) before the first reading..

Arduino ESP8266 01 MQTT Raspberry pi

I want to use ESP 8266 01 and arduino uno as client in MQTT. The code For ESP8266 01 is successfully compiled and I'M getting errors in Arduino uno
The error is 'messageTemp' was not declared in this scope
Amd also I have a thought of using stm32xx in client.
If I compile for that
exit status 1
ISO C++ forbids comparison between pointer and integer [-fpermissive]
above is the error I'm getting
1)ESP code
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
if(topic=="home/office/esp1/gpio2"){
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
// digitalWrite(ledGPIO2, HIGH);
Serial.print("On");
}
else if(messageTemp == "0"){
// digitalWrite(ledGPIO2, LOW);
Serial.print("Off");
}
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("home/office/esp1/gpio2");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Code for Arduino UNO
void setup(){
Serial.begin(9600);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
String messageTemp;
}
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
void loop ()
{
if (Serial.available()){
char topic = Serial.read();
{
if (topic=="home/office/esp1/gpio2")
{
Serial.print("Changing GPIO 2 to ");
if(messageTemp == "1"){
digitalWrite(12, HIGH);
Serial.print("On");
}
else if(messageTemp == "0")
{
digitalWrite(12, LOW);
Serial.print("Off");
}
}}}}
ESP code doesn't look the whole source code you provided. In case of Arduino UNO, if you're intending to use messageTemp as a global variable, then you need to declare it only one time outside of functions. In the above code, you declared it twice in setup() and callback(), then those are considered as local variables. Even in loop(), there's no declaration, this should create the compile error.

Resources