#include <WiFi.h>
#include <HTTPClient.h>
// -------------------------
// Wi-Fi Settings
// -------------------------
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// -------------------------
// ThingSpeak Settings
// -------------------------
const char* server = "http://api.thingspeak.com/update";
String apiKey = "E3RP71MA6BCU57FY"; // Replace with your API key
// -------------------------
// Ultrasonic Sensor Pins
// -------------------------
const int trigPin = 5; // Trigger pin
const int echoPin = 18; // Echo pin
// -------------------------
// Tank parameters
// -------------------------
float tankHeight = 100.0; // Tank height in cm
float fullThreshold = 90.0; // Water level % considered full
float lowThreshold = 10.0; // Water level % considered low
// Variables
long duration;
float distance;
float waterLevel;
String tankStatus;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi");
}
void loop() {
// Measure distance
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Calculate water level
waterLevel = ((tankHeight - distance) / tankHeight) * 100;
// Calculate tank status
if (waterLevel >= fullThreshold) {
tankStatus = "Full";
} else if (waterLevel <= lowThreshold) {
tankStatus = "Low";
} else {
tankStatus = "Normal";
}
// Print values on Serial Monitor
Serial.print("Distance: "); Serial.print(distance); Serial.print(" cm | ");
Serial.print("Water Level: "); Serial.print(waterLevel, 1); Serial.print("% | ");
Serial.print("Tank Status: "); Serial.println(tankStatus);
// Send data to ThingSpeak
if(WiFi.status() == WL_CONNECTED){
HTTPClient http;
String url = server;
url += "?api_key=" + apiKey;
url += "&field1=" + String(distance);
url += "&field2=" + String(waterLevel, 1);
url += "&field3=" + String(tankStatus == "Full" ? 1 : (tankStatus == "Low" ? -1 : 0));
http.begin(url);
int httpResponseCode = http.GET();
if(httpResponseCode>0){
Serial.println("Data sent to ThingSpeak successfully");
} else {
Serial.println("Error sending data to ThingSpeak");
}
http.end();
}
delay(20000); // Send data every 20 seconds (ThingSpeak free limit: 15s min)
}