#include <Arduino.h>
#include <WiFi.h>
#include <DHT.h>
#include <PubSubClient.h>
#define LEDPIN 2
#define DHTPIN 4
const char *ssid = "Wokwi-GUEST";
const char *mqtt_broker = "broker.emqx.io";
const size_t mqtt_port = 1883;
const char *mqtt_client_id = "mqttx_40ffacce";
const char *mqtt_topic = "fwwz/topic";
DHT dht(DHTPIN, DHT22);
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void wifi_connect()
{
WiFi.begin(ssid);
Serial.print("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Connected to WiFi");
}
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
if (client.connect(mqtt_client_id))
{
Serial.println("Connected to MQTT Broker!");
client.subscribe(mqtt_topic);
client.publish(mqtt_topic, "Hello from ESP32");
}
else
{
Serial.print("Failed to connect to MQTT Broker. State: ");
Serial.println(client.state());
delay(5000);
}
}
}
void setup()
{
Serial.begin(115200);
// put your setup code here, to run once:
pinMode(LEDPIN, OUTPUT);
wifi_connect();
client.setServer(mqtt_broker, mqtt_port);
reconnect();
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
}
Serial.println();
}
void loop()
{
while (client.loop())
{
// put your main code here, to run repeatedly:
digitalWrite(LEDPIN, HIGH);
sleep(1000);
digitalWrite(LEDPIN, LOW);
sleep(1000);
}
}