#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
int ledPin = 19; // the number of the LED pin
int ledState = LOW; // ledState used to set the LED
long previousMillis = 0; // will store last time LED
int interval = 1000; // interval at which to blink (milliseconds)
int LED = 19;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "Longdick";
int PORTNUM = 1883;
void setup_wifi()
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED )
{
delay(1000);
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 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];
}
/// Handle your topics and payload here
// Example
if (topic == "Longdick/room/ADC")
{
{
Serial.print("eric kwa");
Serial.println(messageTemp);
}
}
}
void MQTTSubscribe()
{
// Subsccribe to your topics here
client.subscribe("Longdick/room/ADC");// example
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void setup()
{
Serial.begin(9600);
delay(5000);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
}
void loop()
{
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
int adcRes =analogRead(A5);
char snum[10];
// Convert adcRes to string[buf]
itoa (adcRes, snum, 10);
client.publish("Longdick/room/ADC", snum);
/// You can publish your codes here
/// Use non-block codes like millis()
}