#include <WiFi.h>
#include <PubSubClient.h>
// Pot pin used is 34
#define varvolt 34 // GPIO 34
// Replace with your Wi-Fi credentials
const char* ssid = "Wokwi-GUEST"; // Your Wi-Fi SSID
const char* password = ""; // Your Wi-Fi password
// MQTT Broker settings
const char* mqtt_server = "broker.emqx.io";
const int mqtt_port = 1883; // Standard MQTT port
// MQTT Topics
#define POT_TOPIC "home/esp32/var"
// Initialize DHT sensor
// Wi-Fi and MQTT clients
WiFiClient espClient;
PubSubClient client(espClient);
// Function to connect to Wi-Fi
void setup_wifi() {
delay(10);
// Connect to Wi-Fi
Serial.println();
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
// Reconnect to MQTT if disconnected
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32Client-" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
// Start the Serial Monitor
Serial.begin(115200);
// Connect to Wi-Fi
setup_wifi();
// Input
pinMode(varvolt, INPUT);
// Set MQTT server
client.setServer(mqtt_server, mqtt_port);
}
void loop() {
if (!client.connected()) {
reconnect(); // Reconnect if the connection to MQTT is lost
}
// Read potentiometer value and print on the serial monitor
int value=analogRead(varvolt);
Serial.println(value);
// Publish pot value to MQTT broker on separate topics
client.publish(POT_TOPIC, String(value).c_str());
// Wait before publishing again
delay(5000); // Publish every 5 seconds
}