#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
int YLED = 19;
int ledPin = 18;
int ledState = LOW;
long previousMillis = 0;
int interval = 2000;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
//Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_RM123";
int PORTNUM = 1883;
void setup_wifi()
{
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED )
{
delay(2000);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("Given IP by the router to ESP32 is ");
Serial.println(WiFi.localIP());
}
void connectMQTT()
{
while(!client.connected() )
{
Serial.println("Connecting to MQTT ...");
if (client.connect(espClientName) ) //, mqttUser, mqttPassword) )
{
Serial.println("Connected");
MQTTSubscribe();
}
else
{
Serial.print("Failed with state ");
Serial.print(client.state() );
delay(2000);
}
}
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void MQTTSubscribe()
{
// Subsccribe to your topics here
client.subscribe("RM123/room/analog"); // example
client.subscribe("RM123/room/analog");
}
void callback(String topic, byte* payload, unsigned int length)
{
String messageTemp;
Serial.print("Message received in topic: ");
Serial.print(topic);
Serial.print(" length is: ");
Serial.println(length);
Serial.print("Data received from broker: ");
for (int i = 0; i<length; i++)
{
Serial.print( (char)payload[i] );
messageTemp += (char)payload[i];
}
if (topic == "RM123/room/analog")
{
Serial.print("\Yellow LED is ");
if (messageTemp == "On")
{
Serial.print("On");
digitalWrite(YLED, LOW);
Serial.print("\nYellow LED turned On ");
}
else
{
Serial.print("Off");
digitalWrite(YLED, HIGH);
Serial.print("\nYellow LED turned Off \n");
}
}
if (topic == "RM123/room/analog")
{
Serial.println(messageTemp);
}
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(YLED, OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
// put your main code here, to run repeatedly:
long currentMillis = millis();
if ( currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis; // save the last time you blinked the LED
if (ledState == LOW)
{
ledState = HIGH;
client.publish("RM123/room/LED", "Off");
}
else
{
ledState = LOW;
client.publish("RM123/room/LED", "On");
}
digitalWrite(ledPin, ledState);
int adcRes = analogRead(A5);
char snum[10]; // Adjust the size based on the maximum expected value of adcRes
itoa(adcRes, snum, 10);
client.publish("RM123/room/analog",snum);
Serial.print("The ADC reading (integer) is: ");
Serial.println(adcRes);
Serial.print("The ADC reading (string) is: ");
Serial.println(snum);
float voltage = (float) adcRes * 3.3 / 4095;
Serial.print("The voltage is ");
Serial.println( voltage );
}
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
}