#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);
//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
client.subscribe("espClientName"); // example
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
//client.setCallback(callback);
}
void setup()
{
Serial.begin(9600);
delay(5000);
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)
{
// Read soil moisture value
int soilMoisture = analogRead(analogPin);
// Print the soil moisture value to the Serial Monitor
Serial.print("Soil Moisture: ");
Serial.println(soilMoisture);
// Categorize soil moisture into different ranges and create payload
char payload[10];
if (soilMoisture >= 0 && soilMoisture <= 800)
{
snprintf(payload, sizeof(payload), "DRY");
}
else if (soilMoisture > 800 && soilMoisture <= 2000)
{
snprintf(payload, sizeof(payload), "Normal");
}
else if (soilMoisture > 2000 && soilMoisture <= 4095)
{
snprintf(payload, sizeof(payload), "WET");
}
else
{
snprintf(payload, sizeof(payload), "");
}
// Publish soil moisture category to MQTT
client.publish("BENOKJ", payload);
// Your other non-blocking code can go here
delay(1500);
previousMillis = currentMillis; // Save the current time for the next interval
}
}