#include <EasyUltrasonic.h>
#include <PubSubClient.h>
#include <WiFi.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns and 2 rows
// Define your WiFi credentials
// const char *ssid = "Mi A3";
// const char *password = "9800bero";
const char *ssid = "Wokwi-GUEST";
const char *password = "";
// Define your MQTT broker information
const char *mqtt_server = "192.168.1.101";
// const char *mqtt_server = "test.mosquitto.org";
const int mqtt_port = 1883;
// Define MQTT topics
const char *distance_topic = "sanu/height_sonar";
const char *volume_topic1 = "sanu/volume_sonar";
const char *volume_topic2 = "sanu/volume_gravity";
const char *height_topic = "sanu/height_gravity";
const char *resetTopic = "sanu/device1/reset";
const float OffSet = 0.465;
const float tankRadius = 0.5;
const float tankLength = 1.5;
float meanDistance = 0;
int count = 0;
int sum = 0;
#define LED_PIN 13
#define TRIGGER_PIN 4
#define ECHO_PIN 5
EasyUltrasonic ultrasonic; // Create the ultrasonic object
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long time_now = 0;
const int period = 10000;
void setup_wifi() {
Serial.println();
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
if (millis() >= time_now + period) {
ESP.restart();
}
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived on topic [");
Serial.print(topic);
Serial.print("] Payload: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
// Handle LED control messages
if (String(topic) == resetTopic) {
if (message == "reset") {
Serial.println("Resetting ESP8266...");
delay(1000);
// ESP.wdtDisable(); // Disable Watchdog Timer
ESP.restart(); // Perform a software reset
}
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("espClient")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
float waterLevel() {
const int levelDetectionPin = 36;
const float Vref = 3.3;
const float g = 9.81;
float V = analogRead(levelDetectionPin) * Vref / 4096; // Sensor output voltage
float P = (V)*250; // Calculate water pressure
// float P = (V - OffSet) * 250; // Calculate water pressure
Serial.print("Voltage:");
Serial.print(V, 3);
Serial.println("V");
Serial.print(" Pressure:");
Serial.print(P, 1);
Serial.println(" KPa");
float Height = (P / g);
Serial.print(" Height:");
Serial.print(Height);
Serial.println(" Metre");
return Height;
}
float calculateWaterVolume(float height) {
// Calculate water volume based on water height
if (height >= 0 && height <= tankRadius * 2) {
float angle = acos((tankRadius - height) / tankRadius);
float waterArea = angle * tankRadius * tankRadius - (tankRadius - height) * sqrt(2 * tankRadius * height - height * height);
float waterVolume = waterArea * tankLength;
Serial.print("Volume of water in the tank: ");
Serial.print(waterVolume * 1000);
Serial.println("Litre");
return waterVolume;
} else {
Serial.println("Error:calculated height is either '-Ve' or greater than tank diameter");
return 0; // Or any other appropriate error code
}
}
void publishData(const char *topic, float value) {
char message[20]; // Adjust buffer size as needed
sprintf(message, "%.2f", value);
client.publish(topic, message);
}
void setupLCD() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.connect("espClient");
client.setCallback(callback);
client.subscribe(resetTopic);
client.setCallback(callback);
pinMode(LED_PIN, OUTPUT);
setupLCD();
ultrasonic.attach(TRIGGER_PIN, ECHO_PIN); // Attaches the ultrasonic sensor on the specified pins on the ultrasonic object
// ultrasonic.attach(TRIGGER_PIN, ECHO_PIN, 3, 300); // Uncomment this line and comment the above line if you are using the Ping))) ultrasonic sensor
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Measure height using pressure sensor
float height = waterLevel();
// float distance = sonar.ping_cm();
float distanceCM = ultrasonic.getDistanceCM(); // Read the distance in centimeters
float volume_gravity = calculateWaterVolume(height);
if (distance != 0) {
count++;
sum = sum + distance;
if (count == 100) {
meanDistance = sum / count;
float volume_sonar = calculateWaterVolume(tankRadius * 2 - meanDistance / 100);
count = 0;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("distance:");
lcd.print(meanDistance, 2);
lcd.setCursor(0, 1);
lcd.print("Water:");
lcd.print(volume_sonar * 1000, 2);
publishData(distance_topic, distance);
publishData(volume_topic1, volume_sonar * 1000); //m^3->litre
sum=0;
}
}
// Publish data to MQTT
publishData(height_topic, height);
publishData(volume_topic2, volume_gravity*1000);//m^3->litre
delay(10000); // Adjust the delay based on your requirements
}