While trying to setup an ESP32 as mqtt publisher I am getting strange errors. Here is my code:
#include "mqttSetup.h"
#include <WiFi.h>
#include <PubSubClient.h>
static byte httpFailCounter = 0;
byte counter = 0;
const char *ssid = "SSID";
// const char *password = "xxxxx";
const char *passphrase = "xxxxx";
WiFiClient espClient;
const char *mqtt_server = "192.168.1.39";
const int mqttPort = 1883;
const char *mqttUser = "xxxx";
const char *mqttPassword = "xxxxx";
PubSubClient pubClient(espClient);
pubClient.setServer(mqtt_server, mqttPort);
void checkConnection()
{
if (WiFi.status() == WL_CONNECTED)
{
counter = 0; //reset counter
}
else if (WiFi.status() != WL_CONNECTED)
{
WiFi.begin(ssid, passphrase);
}
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
counter++;
if (counter >= 60)
{
ESP.restart();
}
}
}
void reconnect()
{
while (!pubClient.connected())
{
Serial.print("Attempting MQTT connection...");
// Create a random client ID
const char *clientID = "ESP32D-MQTT";
// Attempt to connect
if (pubClient.connect(clientID))
{
Serial.println("connected");
// Once connected, publish an announcement...
pubClient.publish("outTopic", "Hello from ESP");
// ... and resubscribe
// client.subscribe("inTopic");
}
else
{
Serial.print("failed, rc=");
Serial.print(pubClient.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
I don't understand why the compiler is spitting out the following two errors:
this declaration has no storage class or type specifier (referring to my pubClient declaration)
expected a ';'
It doesn't have any issue when I declare the pubClient but at the line :
pubClient.setServer(mqtt_server, mqttPort);
where I use the pubClient it gives the error.
Besides I don't see any ; missing in the code.
Could you please help me figure out the source of error?
Header file for this code chunk
#ifndef MQTTSETUP_H
#define MQTTSETUP_H
void checkConnection();
void reconnect();
#endif
------------ Main sketch---------
#include <Arduino.h>
#include "Wire.h"
#include "tempSensor.h"
#include "mqttSetup.h"
void setup()
{
Wire.begin();
Serial.begin(115200);
while (!Serial)
;
shtBegin();
checkConnection();
}
void loop()
{
uint32_t newTime = millis();
static uint32_t oldTime = 0;
static uint32_t t2 = 0;
float temp = 0.0;
float humid = 0.0;
char senVals[50];
if (newTime - oldTime >= 10000)
{
oldTime = newTime;
readsht(temp, humid);
snprintf(senVals, 50, "Temp: %.2f Humid: %.2f", temp, humid);
Serial.println(senVals);
}
}