//Including the required libraries
#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <EEPROM.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); // Initialising the LCD
//Uploading the Adafruit credentials
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "Subi_7"
#define AIO_KEY "aio_dcLZ42uPJScT29nIqWYqEZ72xQ3m"
WiFiClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
//setting up MQTT publish to send data to required feed in adafruit
Adafruit_MQTT_Publish send = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/water-level");
// Declaring the required variables
long duration, inches;
int set_val, percentage;
bool pump;
// Setting up the basic requirements
void setup() {
lcd.begin(16, 2); // Initialising the LCD
lcd.print("WATER LEVEL:");
lcd.setCursor(0, 1);
lcd.print("PUMP: OFF");
// Initialising the pin modes
pinMode(8, OUTPUT);
pinMode(9, INPUT);
pinMode(12, OUTPUT);
set_val = EEPROM.read(0); // Reading the values
if (set_val > 150) set_val = 150;
Serial1.print("Connecting to WiFi\n");//code to connect to wifi
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial1.print(".");
}}
void connect() {
Serial1.print(F("Connecting to Adafruit IO... "));
int8_t ret;
while ((ret = mqtt.connect()) != 0) {
switch (ret) {
case 1: Serial1.println(F("Wrong protocol")); break;
case 2: Serial1.println(F("ID rejected")); break;
case 3: Serial1.println(F("Server unavail")); break;
case 4: Serial1.println(F("Bad user/pass")); break;
case 5: Serial1.println(F("Not authed")); break;
case 6: Serial1.println(F("Failed to subscribe")); break;
default: Serial1.println(F("Connection failed")); break;
}
if(ret >= 0)
mqtt.disconnect();
Serial1.println(F("Retrying connection..."));
delay(10000);
}
Serial1.println(F("Adafruit IO Connected!"));
}
void loop() {
// Trigger
digitalWrite(3, LOW);
delayMicroseconds(2);
digitalWrite(8, HIGH);
delayMicroseconds(10);
digitalWrite(8, LOW);
duration = pulseIn(9, HIGH);
inches = microsecondsToInches(duration);
// Calculating the water level percentage
percentage = (set_val - inches) * 100 / set_val;
// Displaying the water level in percentage
lcd.setCursor(12, 0);
if (percentage < 0) percentage = 0;
lcd.print(percentage);
lcd.print("% ");
// Switching motor state based on the read value
pump = (percentage < 30); // Set pump state based on the condition
digitalWrite(12, !pump);
// Displaying the pump/motor state
lcd.setCursor(5, 1);
lcd.print("PUMP: ");
lcd.print(pump ? "ON " : "OFF");
}
long microsecondsToInches(long microseconds) {
return microseconds / 74 / 2;
}