#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Pin Definitions
#define DHTPIN PA8
#define DHTTYPE DHT22
#define SWITCH_PIN PA0
#define SOIL_PIN PA7
#define BUZ PB14
#define LED PB13
// Libraries & Objects
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Struct to store sensor data
struct SensorData {
float temp;
float humid;
int soilRaw;
char soilLevel[10]; // "Wet", "Moist", "Dry"
};
// Soil reading history buffer
const int historySize = 5;
int soilHistory[historySize];
int historyIndex = 0;
// Function Prototypes
void readDHT(SensorData *data);
void readSoil(SensorData *data);
void updateDisplayDHT(const SensorData *data);
void updateDisplaySoil(const SensorData *data);
void updateBuzzerAndLED(const SensorData *data);
void setup() {
pinMode(LED, OUTPUT);
pinMode(BUZ, OUTPUT);
pinMode(SWITCH_PIN, INPUT);
dht.begin();
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Sensor System");
delay(2000);
lcd.clear();
}
void loop() {
int switchState = digitalRead(SWITCH_PIN);
SensorData sensor;
lcd.clear();
if (switchState == LOW) {
readDHT(&sensor);
updateDisplayDHT(&sensor);
digitalWrite(LED, LOW);
digitalWrite(BUZ, LOW);
} else {
readSoil(&sensor);
updateDisplaySoil(&sensor);
updateBuzzerAndLED(&sensor);
}
delay(2000);
}
// === Function Definitions ===
void readDHT(SensorData *data) {
data->temp = dht.readTemperature();
data->humid = dht.readHumidity();
}
void readSoil(SensorData *data) {
data->soilRaw = analogRead(SOIL_PIN);
// Add to history buffer (circular)
soilHistory[historyIndex++] = data->soilRaw;
if (historyIndex >= historySize) historyIndex = 0;
if (data->soilRaw < 1000) {
strcpy(data->soilLevel, "Wet");
} else if (data->soilRaw < 2500) {
strcpy(data->soilLevel, "Moist");
} else {
strcpy(data->soilLevel, "Dry");
}
}
void updateDisplayDHT(const SensorData *data) {
if (isnan(data->temp) || isnan(data->humid)) {
lcd.setCursor(0, 0);
lcd.print("DHT Read Error");
} else {
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(data->temp, 1);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Humid: ");
lcd.print(data->humid, 1);
lcd.print(" %");
}
}
void updateDisplaySoil(const SensorData *data) {
lcd.setCursor(0, 0);
lcd.print("Soil Moisture:");
lcd.setCursor(0, 1);
lcd.print("Raw:");
lcd.print(data->soilRaw);
lcd.print(" ");
lcd.print(data->soilLevel);
}
void updateBuzzerAndLED(const SensorData *data) {
if (strcmp(data->soilLevel, "Moist") == 0) {
digitalWrite(LED, LOW);
digitalWrite(BUZ, LOW);
} else {
digitalWrite(LED, HIGH);
digitalWrite(BUZ, HIGH);
}
}