#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define TDS_PIN 34
#define PH_PIN 35
#define TURB_PIN 32
#define LED 25
#define BUZZER 26
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverURL = "https://aqua-alert-wshl.onrender.com/data";
float tds_base = 0;
float ph_base = 0;
float turb_base = 0;
bool baselineSet = false;
int readSensor(int pin) {
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += analogRead(pin);
delay(5);
}
return sum / 10;
}
void postToServer(int tds, int ph, int turb, bool alert) {
if (WiFi.status() != WL_CONNECTED) return;
WiFiClientSecure client;
client.setInsecure();
HTTPClient http;
http.begin(client, serverURL);
http.addHeader("Content-Type", "application/json");
StaticJsonDocument<128> doc;
doc["tds"] = tds;
doc["ph"] = ph;
doc["turb"] = turb;
doc["alert"] = alert;
String body;
serializeJson(doc, body);
int httpCode = http.POST(body);
Serial.printf("HTTP: %d\n", httpCode);
http.end();
}
void setup() {
Serial.begin(115200);
pinMode(LED, OUTPUT);
pinMode(BUZZER, OUTPUT);
analogReadResolution(12);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected");
delay(3000);
}
void loop() {
int tds_val = readSensor(TDS_PIN);
int ph_val = readSensor(PH_PIN);
int turb_val = readSensor(TURB_PIN);
Serial.printf("TDS: %d | pH: %d | Turbidity: %d\n", tds_val, ph_val, turb_val);
if (tds_val <= 0 || ph_val <= 0 || turb_val <= 0) return;
if (tds_val > 3000 || ph_val > 3000 || turb_val > 3000) return;
if (!baselineSet) {
tds_base = tds_val;
ph_base = ph_val;
turb_base = turb_val;
baselineSet = true;
}
if (tds_base == 0) tds_base = 1;
if (ph_base == 0) ph_base = 1;
if (turb_base == 0) turb_base = 1;
float tds_dev = abs(tds_val - tds_base) * 100.0 / tds_base;
float ph_dev = abs(ph_val - ph_base) * 100.0 / ph_base;
float turb_dev = abs(turb_val - turb_base) * 100.0 / turb_base;
bool isAlert = (tds_dev > 20 || ph_dev > 20 || turb_dev > 20);
digitalWrite(LED, isAlert);
digitalWrite(BUZZER, isAlert);
if (isAlert) Serial.println("ALERT!");
postToServer(tds_val, ph_val, turb_val, isAlert);
delay(2000);
}