#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include <DHT_U.h>
#include <Adafruit_Sensor.h>
#define DHTPIN 32
//const int analogLightPin = 35; // For Light sensor
//const int analogPin = 33; // For moisture sensor
unsigned long previousMillis = 0;
const long interval = 500; // Read every 500 milliseconds
// DHT parameters
#define DHTTYPE DHT22 // DHT 11
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;
// Parameters for using non-blocking delay
String msgStr = ""; // MQTT message buffer
float temp, hum;
//WIFI
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client"; // yourStudentID must be unique
int PORTNUM = 1883;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
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 MQTTSubscribe()
{
// Subscribe to your topics here
// Add subscription if needed
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
// client.setCallback(callback);
}
void setup()
{
Serial.begin(9600);
delay(5000);
// Initialize device.
dht.begin();
// Get temperature sensor details.
sensor_t sensor;
dht.temperature().getSensor(&sensor);
dht.humidity().getSensor(&sensor);
setup_wifi();
setup_MQTT();
}
void loop()
{
if (!client.connected())
{
connectMQTT();
}
client.loop();
unsigned long currentMillis = millis(); // Get the current time // Check if the specified interval has passed
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
// Read temperature and humidity
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature))
{
Serial.println(F("Error reading temperature!"));
}
else
{
Serial.print(F("Temperature: "));
temp = event.temperature;
Serial.print(temp);
Serial.println(F("°C"));
}
// Get humidity event and print its value
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity))
{
Serial.println(F("Error reading humidity!"));
}
else
{
Serial.print(F("Humidity: "));
hum = event.relative_humidity;
Serial.print(hum);
Serial.println(F("%"));
}
// Publish temperature and humidity to MQTT
msgStr = String(temp) + "," + String(hum) + ",";
byte arrSize = msgStr.length() + 1;
char msg[arrSize];
msgStr.toCharArray(msg, arrSize);
client.publish("iotben", msg);
msgStr = "";
delay(1500);
}
}