Hello, I am asking a question for the first time in Stackoverflow so please pardon my mistakes for this time. I am using VScode IDE with PlatformIO to use an ESP32-WROOM-32U to connect to a Wi-Fi and receive/send integers to another component via MQTT protocol. I have confirmed that the controlleris able to connect to a wifi successfully.
Withot inserting extern PubSubClient client; I had "client was not declared in this scope" error for both client.loop() and client.setServer(MQTT_SERVER, 1883). After the insertion of extern to let the compiler understand that "PubSubClient.h" should be accessible for declaration I get the following error code:
c:/users/user/.platformio/packages/toolchain-xtensa-esp32/bin/../lib/gcc/xtensa-esp32-elf/8.4.0/../../../../xtensa-esp32-elf/bin/ld.exe: .pio\build\esp32dev\src\main.cpp.o:(.literal._Z5setupv+0x2c): undefined reference to `client'
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\esp32dev\firmware.elf] Error 1
I have tried using a couple fo other things I found online but they didn'T help. Here are my files:
main.cpp file that will be executed by the ESP32:
#include <Arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <ArduinoJson.h>
#include <ArduinoJson.hpp>
const char *SSID = "SSID_NAME";
const char *PASSWORD = "PASSWORD_PLACEHOLDER";
const char *MQTT_SERVER = "192.168.1.109"; // Change this to your MQTT broker IP address
//WiFiClient espClient;
//PubSubClient client(espClient);
extern PubSubClient client;
void callback(char* topic, byte* payload, unsigned int length) {
// handle the incoming message here
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
Serial.println(message);
}
void setup() {
Serial.begin(921600);
pinMode(26, OUTPUT);
WiFi.mode(WIFI_AP_STA);
WiFi.disconnect();
int n = WiFi.scanNetworks();
if (n == 0) {
Serial.println("no networks found");
}
else{
Serial.print(n);
Serial.println(" networks found");
}
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println(WiFi.localIP());
client.setServer(MQTT_SERVER, 1883);
while (!client.connect("ESP32Client")) {
delay(1000);
Serial.println("Connecting to MQTT server...");
}
Serial.println("Connected to MQTT server");
client.subscribe("topic");
client.setCallback(callback);
}
void loop() {
digitalWrite(26, WiFi.status() == WL_CONNECTED);
delay(800);
// Your code here
client.loop();
}
The platformio.ini file:
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 921600
lib_deps =
knolleary/PubSubClient@^2.8
bblanchon/ArduinoJson@^6.20.1