Mega2560 + ESP8266 + MQTT (PubSubClient error)

Hi,

I making a project with the mega connected with ESP8266 via hardware serial1.
Without the PubSubClient liberary i have managed to connect to my wifi.

Now i want to publish something to my own (rasbarryPi) Hassio MQTT server.
For that i need the PubSubCient liberary.
But this liberary asks for a PubSubClient client("?????");
What ever i put in stead of the questionsmarks i get errors.

When connecting to MQTT via wemosD1 i use the ESP8266WiFi.h;
But on the mega that doesn’t work. On the mega i have to use ESP8266_Lib.h;
This liberary is included in the blynk default example skatches under -> boards wifi -> ESP8266 shield.

Different liberary so copie - past from one skatch to the other doesn’t work.

Kan some please take a look? Maybe PubSub liberary doesn’t work with hardware serial com with esp8266?

Working code on WemosD1 with mqtt:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
const char* ssid = "******";
const char* password = "******";
const char* mqtt_server = "******";

WiFiClient espClient;
PubSubClient client(espClient);

int SwitchedPin = D4;
String afzuiging;
String strTopic;
String strPayload;

void setup_wifi() {
 Serial.begin(115200);
  delay(100);
 
  // We start by connecting to a WiFi network
 
  Serial.println();
  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.println("WiFi connected");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  payload[length] = '\0';
  strTopic = String((char*)topic);
Serial.println(strTopic);
  
  if(strTopic == "ha/afzuiging")
    {
    afzuiging = String((char*)payload);
    if(afzuiging == "ON")
      {
        Serial.println("ON");
        digitalWrite(SwitchedPin, LOW);
      }
    else
      {
        Serial.println("OFF");
        digitalWrite(SwitchedPin, HIGH);
      }
    }
}
 
 
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient","admin","admin")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.subscribe("ha/#");
    } 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()
{
  setup_wifi(); 
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  pinMode(SwitchedPin, OUTPUT);
  digitalWrite(SwitchedPin, LOW);
}
 
void loop()
{
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

And this is the Mega NOT working code:




/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <PubSubClient.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "************";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "*****";
char pass[] = "********";

//Hardware Serial on Mega, Leonardo, Micro...
#define EspSerial Serial1
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);


///////////////////////////////////MQTT//////////////////////////////////
PubSubClient client(ESP8266 wifi);
String afzuiging;
String strTopic;
String strPayload;


////////////////////////////////////TFT/////////////////////////////////

#include <Adafruit_GFX.h>
#include <MCUFRIEND_kbv.h>
MCUFRIEND_kbv tft;
#include <TouchScreen.h>
#define MINPRESSURE 200
#define MAXPRESSURE 1000


#include <Fonts/FreeSans9pt7b.h>
#include <Fonts/FreeSans12pt7b.h>
#include <FreeDefaultFonts.h>

// ALL Touch panels and wiring is DIFFERENT
// copy-paste results from TouchScreen_Calibr_native.ino
const int XP = 8, XM = A2, YP = A3, YM = 9; //320x240 ID=0x9341
const int TS_LEFT = 73, TS_RT = 896, TS_TOP = 124, TS_BOT = 910;

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

Adafruit_GFX_Button on1_btn, on2_btn, on3_btn, off_btn;

int pixel_x, pixel_y;     //Touch_getXY() updates global vars
bool Touch_getXY(void)
{
  TSPoint p = ts.getPoint();
  pinMode(YP, OUTPUT);      //restore shared pins
  pinMode(XM, OUTPUT);
  digitalWrite(YP, HIGH);   //because TFT control pins
  digitalWrite(XM, HIGH);
  bool pressed = (p.z > MINPRESSURE && p.z < MAXPRESSURE);
  if (pressed) {
    pixel_x = map(p.y, TS_LEFT, TS_RT, 0, tft.width()); //.kbv makes sense to me
    pixel_y = map(p.x, TS_TOP, TS_BOT, 0, tft.height());
  }
  return pressed;
}

#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

#define Speed1Pin 31
#define Speed2Pin 32

void callback(char* topic, byte* payload, unsigned int length) {
  payload[length] = '\0';
  strTopic = String((char*)topic);
Serial.println(strTopic);
  
  if(strTopic == "ha/afzuiging")
    {
    afzuiging = String((char*)payload);
    if(afzuiging == "ON")
      {
        Serial.println("ON");
       // digitalWrite(SwitchedPin, LOW);
      }
    else
      {
        Serial.println("OFF");
       // digitalWrite(SwitchedPin, HIGH);
      }
    }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClient","*****","*******")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.subscribe("ha/#");
    } 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(void)
{
  Serial.begin(115200);
  pinMode(Speed1Pin, OUTPUT);
  pinMode(Speed2Pin, OUTPUT);
  uint16_t ID = 0x9341;
  tft.begin(ID);
  tft.setRotation(1);            //PORTRAIT
  tft.fillScreen(BLACK);
  tft.drawRect(0, 0, 319, 240, WHITE);

  tft.setFont(&FreeSans9pt7b);
  
  tft.setCursor(50, 30);
  tft.setTextColor(WHITE);
  tft.setTextSize(1);
  tft.print("WIFI CONNECTING...");

///////////////////////////////WIFI/////////////////////
    EspSerial.begin(ESP8266_BAUD);
    Blynk.begin(auth, wifi, ssid, pass);
    
  /////////////////////////MQTT///////////////////////

   client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

//////////////////////////////////////////////////
  tft.fillScreen(BLACK);
  tft.drawRect(0, 0, 319, 240, WHITE);
  tft.setCursor(50, 30);
  tft.setTextColor(WHITE);
  tft.setTextSize(1);
  tft.print("CENTRALE AFZUIGING");
  tft.fillRect(150, 50, 155, 100, RED);
}

void loop(void)
{
  /////////////////////WIFI////////////////////////////
  Blynk.run();
  
  ////////////////////MQTT////////////////////////////
 if (!client.connected()) {
    reconnect();
  }
  client.loop();
////////////////////////////////////////////////////


  //__________________________________________________

  }


}

This is the arduino IDE compile error:

Arduino:1.8.9 (Mac OS X), Board:“Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)”

/var/folders/wf/4vz3b4_x6658s321739l7vjc0000gn/T/arduino_modified_sketch_921032/Afzuiging_TFT_side_V4_test_HASSio.ino: In function ‘void reconnect()’:
Afzuiging_TFT_side_V4_test_HASSio:158:18: error: request for member ‘connected’ in ‘client’, which is of non-class type ‘PubSubClient(ESP8266)’
while (!client.connected()) {
^

  ^

exit status 1
request for member ‘connected’ in ‘client’, which is of non-class type ‘PubSubClient(ESP8266)’

I know you are not expecting this kind of answer, but… For your peace of mind MOVE your main code to ESP8266, and if you stil need the MEGA for some kind of operations leave that part of code to MEGA. For communication you can off course use SERIAL, but the “direction” would be reversed. ESP is working flawlessly with MQTT, has much better (“native” ) WIFi handling, and overall performs betterin network env.

Hi,

Thanks for your time.

Well i don’t know if it is then possible to accomplish my goal?
See, i use a tft screen UNO/MEGA shield on the Mega to control my speeds of a fan.
and also via blynk app.

If i move the code to esp how can i get buttons states (pressed on the tft screen) to the esp?
Also how do i update the screen with correct button/speed state when using blynk app?

never done this before… you say that is still possible via SERIAL. This means communicating between 2 MCU’s via SERIAL? Isn’t that much harder to do?

thank for your help

Then naturally the button handling and tft driver/routines are left in MEGA. The ESP takes care of Blynk an MQTT communication. The data is exchanged via serial port.

naturally… the hard part for me is “data is exchanged via serial port” :grimacing:

Never than that before. Tried ones long time a go and didn’t succeed…

Do you know/have a example of communicating between 2 MSU’s via SERIAL?
Is there a liberary for?

tnx a lot!

I’m usually creating my “own protocol” - that is really easy (if you are not expecting much more than simple data exchange), but you can check for example the EasyTransfer library. Never used it though, but was planning to do so. There are probably other too…

Personally, I’s use Blynk or MQTT on your device, not both.
If you do need to use both then you should set-up your Wi-Fi connection using a different library then use Blynk.config and Blynk.connect rather than Blynlk.begin.

https://docs.blynk.cc/#blynk-firmware

I use Blynk and MQTT extensivly, but Use Node-Red and Mosquitto running on a Pi and only run MQTT code on my ESP devices.

If you want a proper touch screen then I’d forget the Arduino shield and go with a Nextion connected to an ESP.

Pete.

hi Pete,

Witch library you suggest i could use to be able to use both blynk and mqtt with my hardware?
And use it with blynk.config and blynk.connect.

i want to try this first before try using for example easyTransfer library.

tnx a lot

I don’t use the Arduino/ESP-01 combination, so can’t make any recommendations from personal experience.
You should google to see how non Blynk users are using ESP-01s with Arduinos and go from there.

Pete.

ok. tnx a lot!