#include <WiFi.h>
#include <WebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "ThingSpeak.h"
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak details
WiFiClient client;
unsigned long myChannelNumber = ; // Replace with your ThingSpeak channel number
const char * myWriteAPIKey = ""; // Replace with your Write API Key
// Web server
WebServer server(80);
// Sensor pins
#define ONE_WIRE_BUS 4 // DS18B20 pin
const int phPin = 34;
const int tdsPin = 35;
const int turbidityPin = 32;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float phValue, tdsValue, turbidityValue, temperature;
String waterStatus;
// Function to check water quality
void checkWaterStatus() {
if (phValue >= 6.5 && phValue <= 8.5 &&
tdsValue <= 500 &&
turbidityValue <= 5 &&
temperature >= 20 && temperature <= 35) {
waterStatus = "SAFE";
} else {
waterStatus = "UNSAFE";
}
}
// Handle webpage request
void handleRoot() {
String html = "<!DOCTYPE html><html><head><title>Water Quality</title>";
html += "<style>body{font-family:Arial;text-align:center;} .safe{color:green;font-size:24px;} .unsafe{color:red;font-size:24px;}</style></head><body>";
html += "<h1>Water Quality Monitor</h1>";
html += "<p>Temperature: " + String(temperature, 2) + " °C</p>";
html += "<p>pH: " + String(phValue, 2) + "</p>";
html += "<p>TDS: " + String(tdsValue, 2) + " ppm</p>";
html += "<p>Turbidity: " + String(turbidityValue, 2) + " NTU</p>";
html += "<p class='" + (waterStatus=="SAFE"?"safe":"unsafe") + "'>Status: " + waterStatus + "</p>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void setup() {
Serial.begin(115200);
sensors.begin();
// Connect WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500); Serial.print(".");
}
Serial.println("\nWiFi Connected! IP Address: ");
Serial.println(WiFi.localIP());
// Start ThingSpeak
ThingSpeak.begin(client);
// Start web server
server.on("/", handleRoot);
server.begin();
}
void loop() {
// Read sensors
sensors.requestTemperatures();
temperature = sensors.getTempCByIndex(0);
phValue = analogRead(phPin) * (14.0 / 4095.0);
tdsValue = analogRead(tdsPin) * (1000.0 / 4095.0);
turbidityValue = analogRead(turbidityPin) * (100.0 / 4095.0);
checkWaterStatus();
// Print on Serial Monitor
Serial.printf("Temp: %.2f °C | pH: %.2f | TDS: %.2f ppm | Turbidity: %.2f NTU | Status: %s\n",
temperature, phValue, tdsValue, turbidityValue, waterStatus.c_str());
// Send data to ThingSpeak
ThingSpeak.setField(1, temperature);
ThingSpeak.setField(2, phValue);
ThingSpeak.setField(3, tdsValue);
ThingSpeak.setField(4, turbidityValue);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200) {
Serial.println("Data sent to ThingSpeak!");
} else {
Serial.println("Error sending data to ThingSpeak!");
}
// Handle webpage requests
server.handleClient();
delay(15000); // ThingSpeak requires min 15s interval
}