#include <WiFi.h>
#include <PubSubClient.h>
// WiFi Credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "test.mosquitto.org";
const int mqttPort = 1883;
const char* mqttUser = "aaaa";
const char* mqttPassword = "aaaa";
int ValueToSend;
#define ADCpin 36 //pin for potensiometer
#define LED 26 //built-in LED_BUILTIN
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("userid")) { //user id must be unique in case of many users under one topic to avoid conflict/crosstalk information
Serial.println("Connected to MQTT");
client.subscribe("LED"); //SUBSCRIBE TOPIC
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
pinMode(LED, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
//delay(10); // this speeds up the simulation
int ADC = analogRead(ADCpin);
//ValueToSend = map(ADC,0,4095,0,100);
int ValueToSend = 1000*ADC*5/4095;
Serial.println(ValueToSend);
char payload[10]; // buffer array size is proportional to message that wanted to be sent
snprintf(payload, sizeof(payload), "%d", ValueToSend);
client.publish("pubtopic", payload); //PUBLISH TOPIC
// Printing message value on Serial Monitor and waiting
client.loop();
Serial.println();
delay(1000); //adjust interval
}
void callback(String topic, byte* payload, unsigned int length) {
Serial.println();
Serial.print("Message received on topic: ");
Serial.println(topic);
Serial.println("Message: ");
String msg;
if (topic == "LED"){
for (int i = 0; i < length; i++) {
//Serial.print((char)payload[i]);
msg += (char)payload[i];
}
Serial.println(msg);
Serial.print("LED status: ");
if (msg == "ON"){
digitalWrite(LED, HIGH);
Serial.println("ON");
}
else if (msg == "OFF"){
digitalWrite(LED, LOW);
Serial.println("OFF");
}
}
Serial.println();
delay(1000); //adjust interval
}