#include "Secrets.h"
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <ArduinoJson.h>
#include "Publish.h"
#include "DHT.h"
#define DHTPIN 12 // Digital pin connected to the DHT sensor
#define RELAY_PIN 15 // Define the pin where the LED is connected
#define DHTTYPE DHT22 // DHT 22
#define ARRAY_SIZE 10 // Number of readings to store
String readings[ARRAY_SIZE]; // Array to store the readings
int id = 0; // Index to manage the current reading position
float h ;
float t;
// String device_id ="device_id";
LiquidCrystal_I2C lcd(0x27,12,3);
DHT dht(DHTPIN, DHTTYPE);
void initArray(){
for (int i = 0; i < ARRAY_SIZE; i++) {
readings[i] = ""; // Initialize the array with the maximum value (sensor dependent)
}
}
bool checkAllDry() {
for (int i = 0; i < ARRAY_SIZE; i++) {
if (readings[i] != "DRY") { // Check if the reading is not DRY
return false; // If any reading is not dry, return false
}
}
return true; // All readings are dry
}
void updateReadings(String newReading) {
readings[id] = newReading; // Store new reading
id = (id + 1) % ARRAY_SIZE; // Update index to rotate in a FIFO manner
}
void setup()
{
Wire.begin(22, 21); // Initialize the I2C communication with SDA pin 23 and SCL pin 22.
Serial.begin(9600); /// Initialize the serial communication at a baud rate of 9600 bits per second.
lcd.init(); // initialize the lcd
lcd.backlight(); // turn on the backlight
randomSeed(analogRead(0));
Serial.begin(115200);
connectAWS();
dht.begin();
pinMode(RELAY_PIN, OUTPUT);
}
void loop()
{
// int rndNb = random(1, 5);
// String str = "Device_" + String(rndNb);
h = dht.readHumidity();
t = dht.readTemperature();
// device_id = str;
int16_t moist = analogRead(34);
String MoistureState = moist < 370 ? "WET" : moist > 600 ? "DRY" : "Hmd";
updateReadings(MoistureState);
if (id % ARRAY_SIZE == 0) {
if (checkAllDry()) {
Serial.println("All of the last 10 values are dry!");
digitalWrite(RELAY_PIN, HIGH); // Turn LED ON if all values are dry
} else {
Serial.println("Not all of the last 10 values are dry.");
digitalWrite(RELAY_PIN, LOW); // Turn LED OFF if not all values are dry
}
}
lcd.clear();
lcd.print("Moist:");
lcd.print(moist, 1); // Print Moisture with one decimal;
lcd.print(": ");
lcd.print(MoistureState);
// if (isnan(h) || isnan(t) ) // Check if any reads failed and exit early (to try again).
// {
// Serial.println(F("Failed to read from DHT sensor!"));
// return;
// }
lcd.setCursor(0, 1); // Set cursor to the first column and second row
lcd.print("T:"); // Print "T:" (Temperature)
lcd.print(t); // Print temperature with one decimal
lcd.print(" H:"); // Print " H:" (Humidity)
lcd.print(h); // Print humidity with one decimal;
char msg[100];
snprintf(msg, 100, "{\"temperature\": %.2f, \"humidity\": %.2f, \"Moisture\": %d , \"MoistureState\": \"%s\" }", t, h, moist, MoistureState);
client.publish(AWS_IOT_PUBLISH_TOPIC, msg);
client.loop();
delay(3000);
}