#include <WiFi.h>
#include <MQTT.h>
// Wi-Fi and MQTT settings
const char* ssid = "Wokwi-GUEST"; // Replace with your Wi-Fi SSID
const char* password = ""; // Replace with your Wi-Fi password
const char* mqttServer = "broker.mqttdashboard.com"; // Replace with your MQTT broker server
const int mqttPort = 1883; // Specify the MQTT broker's port
const char* mqttUser = ""; // Replace with your MQTT username
const char* mqttPassword = ""; // Replace with your MQTT password
float irradianceValue=0, dcPowerValue=0;
WiFiClient wifiClient;
MQTTClient client;
void setup() {
Serial.begin(115200);
connectToWiFi();
connectToMQTT();
}
void loop() {
client.loop();
dcPowerValue = analogRead(33) * 3.0 / 819;
irradianceValue = analogRead(35) / 819.0;
// Your JSON message creation
String jsonMessage = "{";
jsonMessage += "\"DCPower\":" + String(dcPowerValue) + ",";
jsonMessage += "\"Irradiance\":" + String(irradianceValue);
jsonMessage += "}";
Serial.println(jsonMessage);
if (client.connected()) {
// Your MQTT publish code
Serial.println("Published");
client.publish("wokwi-solar-energy", jsonMessage);
}else{
connectToMQTT();
client.publish("wokwi-solar-energy", jsonMessage);
Serial.println("Published");
}
delay(5000); // Adjust the delay to your preferred update interval
}
void connectToWiFi() {
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
}
void connectToMQTT() {
Serial.println("Connecting to MQTT broker...");
client.begin(mqttServer, mqttPort, wifiClient);
if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed to connect to MQTT broker");
delay(1000);
}
}