#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Define the I2C address for the LCD
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_ROWS 2
// Define pin numbers for the sensors
#define DHTPIN 2
#define DHTTYPE DHT22 // Use DHT22 for better accuracy in the simulation
#define TURBIDITY_PIN A0
// Initialize the DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Initialize the LCD
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_ROWS);
// Chip Select pin for the SD card module
const int chipSelect = 10;
void setup() {
// Start the serial communication for debugging
Serial.begin(9600);
// Initialize the LCD
lcd.begin(LCD_COLUMNS, LCD_ROWS);
lcd.init();
lcd.backlight();
// Initialize the DHT sensor
dht.begin();
// Initialize the SD card
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("Card initialized.");
// Display initial message
lcd.setCursor(0, 0);
lcd.print("Water Mgmt Sys");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(2000);
lcd.clear();
}
void loop() {
// Read temperature from the DHT sensor
float temperature = dht.readTemperature();
// Simulate turbidity value (you can use an analog input or any other method to generate values)
int turbidityValue = analogRead(TURBIDITY_PIN);
// Check if any reads failed and exit early (to try again)
if (isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Open a file for writing
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// If the file is available, write to it:
if (dataFile) {
dataFile.print("Temperature: ");
dataFile.print(temperature);
dataFile.print(" °C");
dataFile.print(" | Turbidity: ");
dataFile.println(turbidityValue);
dataFile.close();
} else {
// If the file isn't open, pop up an error:
Serial.println("error opening datalog.txt");
}
// Print the readings to the serial monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C");
Serial.print(" | Turbidity: ");
Serial.println(turbidityValue);
// Display the readings on the LCD
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Turb: ");
lcd.print(turbidityValue);
// Wait a few seconds between measurements
delay(2000);
}