#include <PubSubClient.h>
#include <WiFi.h>
#define POTENTIOMETER_PIN 12 // GPIO pin connected to potentiometer
#define BUTTON_PIN 14 // GPIO pin connected to button
#define TOPIC_PUBLISH "topic_sensor_value"
const char *SSID = "Wokwi-GUEST"; // Wi-Fi SSID
const char *PASSWORD = ""; // Wi-Fi password
const char *BROKER_MQTT = "broker.hivemq.com";
const char *CLIENTID = "ESP32-wokwi";
WiFiClient espClient;
PubSubClient client(espClient);
bool buttonState = false;
bool lastButtonState = false;
void setup_wifi() {
Serial.print("Connecting to Wi-Fi");
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Wi-Fi connected");
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect(CLIENTID)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
// pinMode(POTENTIOMETER_PIN, INPUT);
// pinMode(BUTTON_PIN, INPUT_PULLUP); // Use INPUT_PULLUP for stable reading
setup_wifi();
client.setServer(BROKER_MQTT, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
bool currentButtonState = digitalRead(BUTTON_PIN) == LOW; // Button pressed
if (currentButtonState && !lastButtonState) {
// Button clicked
float potentiometerValue = analogRead(POTENTIOMETER_PIN); // Read raw ADC value
float voltage = potentiometerValue * (3.3 / 4095.0); // Convert to voltage
char message[50];
sprintf(message, "Potentiometer Voltage: %.2fV", voltage);
Serial.println(message);
// Publish to MQTT
client.publish(TOPIC_PUBLISH, message);
}
lastButtonState = currentButtonState; // Update button state
}