#include <PubSubClient.h>
#include <WiFi.h>
#define POTENTIOMETER_PIN 34 // ESP32 pin GPIO36 (ADC0) connected to Potentiometer pin
//#define LED_PIN 21 // ESP32 pin GPIO21 connected to LED's pin
#define ANALOG_THRESHOLD 1000
int potValue = 0;
float volt = 0.0;
char tempAr1[6];
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void setup() {
setupWiFi();
setupMqtt();
//pinMode(LED_PIN, OUTPUT); // set ESP32 pin to output mode
Serial.begin(115200);
delay(1000);
}
void loop() {
if (!mqttClient.connected()) {
connectToBroker();
}
mqttClient.loop();
potValue = analogRead(POTENTIOMETER_PIN);
volt = (float)potValue / 4095 * 3.3;
//Serial.println(“ADC:”);
//Serial.println(potValue);
//Serial.println(“Volt:”);
//Serial.println(volt);
delay(500);
int analogValue = analogRead(POTENTIOMETER_PIN); // read the input on analog pin
//if (analogValue > ANALOG_THRESHOLD)
//digitalWrite(LED_PIN, HIGH); // turn on LED
//else
//digitalWrite(LED_PIN, LOW); // turn off LED
String(volt, 3).toCharArray(tempAr1, 6);
mqttClient.publish("Pot_read", tempAr1);
Serial.println(tempAr1);
delay(1000);
}
void setupWiFi() {
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void setupMqtt() {
mqttClient.setServer("test.mosquitto.org", 1883);
}
void connectToBroker() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("ESP-8266-000789458")) {
Serial.println("connected");
} else {
Serial.println("failed");
Serial.print(mqttClient.state());
delay(5000);
}
}
}