Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //***********************************************************************************************************************
- //***********************************************[ Included Libraries ]**************************************************
- #include <WiFi.h>
- #include <WiFiClientSecure.h>
- #include <UniversalTelegramBot.h>
- #include "Adafruit_MQTT.h"
- #include "Adafruit_MQTT_Client.h"
- #include <ArduinoJson.h>
- #include <OneWire.h>
- #include <DallasTemperature.h>
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //**************************************************[ Pin Definitions ]**************************************************
- //Pump Relay Connections
- const int pumpRelayPin = 21;
- //TDS Sensor Connections
- const int TdsSensorPin = 34;
- //DS18B20 Sensor Connections
- const int oneWireBus = 4;
- //Ultrasonic Sensor Connections
- const int trigPin = 5;
- const int echoPin = 18;
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //**************************************************[ Web Dashboard Setup ]**********************************************
- /************************* WiFi Access Point *********************************/
- const char* ssid = "BS Home1";
- const char* password = "0554418546";
- /************************* Telegram Setup ************************************/
- #define BOTtoken "7231586324:AAFisXqDehD6vfX9hJ-8isgxaL0ALCqnMDk"
- #define CHAT_ID "985890015"
- /*********************** MQTT Account Setup **********************************/
- #define AIO_USERNAME "project19102024"
- #define AIO_KEY "aio_oONO288tq2G4GFfzGQTyhL3jaNUw"
- #define AIO_SERVER "io.adafruit.com"
- // Using port 8883 for MQTTS
- #define AIO_SERVERPORT 8883
- // Adafruit IO Account Configuration
- // (to obtain these values, visit https://io.adafruit.com and click on Active Key)
- /************ Global State (you don't need to change this!) ******************/
- // WiFiFlientSecure for SSL/TLS support
- WiFiClientSecure 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);
- // io.adafruit.com root CA
- const char* adafruitio_root_ca =
- "-----BEGIN CERTIFICATE-----\n"
- "MIIEjTCCA3WgAwIBAgIQDQd4KhM/xvmlcpbhMf/ReTANBgkqhkiG9w0BAQsFADBh\n"
- "M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6A1oDOGMWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEds\n"
- "b2JhbFJvb3RHMi5jcmwwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEW\n"
- "HGh0dHBzOi8vd3d3LmRpZ2ljZXJ0LmNvbS9DUFMwDQYJKoZIhvcNAQELBQADggEB\n"
- "AIIcBDqC6cWpyGUSXAjjAcYwsK4iiGF7KweG97i1RJz1kwZhRoo6orU1JtBYnjzB\n"
- "c4+/sXmnHJk3mlPyL1xuIAt9sMeC7+vreRIF5wFBC0MCN5sbHwhNN1JzKbifNeP5\n"
- "ozpZdQFmkCo+neBiKR6HqIA+LMTMCMMuv2khGGuPHmtDze4GmEGZtYLyF8EQpa5Y\n"
- "jPuV6k2Cr/N3XxFpT3hRpt/3usU/Zb9wfKPtWpoznZ4/44c1p9rzFcZYrWkj3A+7\n"
- "TNBJE0GmP2fhXhP1D/XVfIW/h0yCJGEiV9Glm/uGOa3DXHlmbAcxSyCRraG+ZBkA\n"
- "7h4SeM6Y8l/7MBRpPCz6l8Y=\n"
- "-----END CERTIFICATE-----\n";
- /****************************** Feeds ***************************************/
- //Data Rate Limit: The free account has a limit of 30 data points per minute
- //e.g. [5] Data points every [10] seconds gives [30] data points every [1 minute]
- //increasing interval between sending data points to avoid restriction on the account
- static unsigned long timeBetweenDataPointsToBeSent = 12000;
- Adafruit_MQTT_Publish distance_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/distance_mqtt");
- Adafruit_MQTT_Publish volume_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/volume_mqtt");
- Adafruit_MQTT_Publish waterLevel_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/waterLevel_mqtt");
- Adafruit_MQTT_Publish temprature_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temprature_mqtt");
- Adafruit_MQTT_Publish tds_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/tds_mqtt");
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //******************************************[ Variables for TDS Sensor ]*************************************************
- #define VREF 3.3 // Reference voltage of ESP32 (3.3V for most ESP32 boards)
- #define ADC_RESOLUTION 4095 // 12-bit ADC resolution for ESP32
- float temperature = 25; // Temperature in Celsius, adjust as needed
- float calibrationFactor = 2; // TDS calibration factor (default 0.5 for most sensors)
- //86 ppm
- int analogValueTDS;
- float voltageTDS;
- float tdsValue;
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //***********************************************[ Read TDS Sensor Function ]********************************************
- void ReadTDSSensor() {
- analogValueTDS = analogRead(TdsSensorPin); // Read analog value from sensor
- voltageTDS = analogValueTDS * VREF / ADC_RESOLUTION; // Convert to voltageTDS
- tdsValue = (voltageTDS / calibrationFactor) * 1000; // Calculate TDS in ppm
- tdsValue = tdsValue / (1.0 + 0.02 * (25 - 25.0)); // Temperature compensation
- Serial.println("-------------------------");
- Serial.print("TDS Value: ");
- Serial.print(tdsValue, 2);
- Serial.println(" ppm");
- Serial.println("-------------------------");
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //**************************************************[ Telegram Setup ]***************************************************
- WiFiClientSecure Sclient;
- UniversalTelegramBot bot(BOTtoken, Sclient);
- unsigned long bot_lasttime;
- unsigned long mqtt_lasttime;
- bool Start = false;
- float value1 = 0;
- float value2 = 0;
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //******************************************[ Variables for Ultrasonic Sensor ]******************************************
- //define sound speed in cm/uS
- #define SOUND_SPEED 0.034
- float radius = 3; //half the diameter in [CM]
- float hight = 30; //hight of the container in [CM]
- long duration;
- float distanceCm;
- float volume_cm3;
- int waterLevel;
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //*****************************************[ Temprature Sensor Setup ]***************************************************
- OneWire oneWire(oneWireBus);
- DallasTemperature sensors(&oneWire);
- float temperatureC;
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //**************************************************[ Main Setup Function ]**********************************************
- void setup() {
- Serial.begin(115200);
- SetupSensors();
- pumpOFF();
- SetupWiFiandTelegramBot();
- bot.sendMessage(CHAT_ID, "ESP32 Started WokWi");
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //**************************************************[ Main Loop Function ]***********************************************
- void loop() {
- ReadDistanceUsingUltrasonicSensor();
- ReceiveMessageFromTelegram();
- ReadTempratureSensor();
- Publish_Sensor_Data();
- ReadTDSSensor();
- if (distanceCm > hight && ) {
- pumpON();
- }
- //delay(500);
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //*************************************************[ Setup Sensors Function ]********************************************
- void SetupSensors() {
- pinMode(pumpRelayPin, OUTPUT);
- pinMode(TdsSensorPin, INPUT);
- pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
- pinMode(echoPin, INPUT); // Sets the echoPin as an Input
- sensors.begin();
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //*************************************************[ Pump Functions ]********************************************
- void pumpON() {
- digitalWrite(pumpRelayPin, 1);
- delay(500);
- }
- void pumpOFF() {
- digitalWrite(pumpRelayPin, 0);
- delay(500);
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //**********************************************[ Setup WiFi and Telegram Function]**************************************
- void SetupWiFiandTelegramBot() {
- // Connect to Wi-Fi
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- Sclient.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
- while (WiFi.status() != WL_CONNECTED) {
- delay(1000);
- Serial.println("Wifi Connected..");
- }
- // Print ESP32 Local IP Address
- Serial.println(WiFi.localIP());
- Serial.print("Retrieving time: ");
- configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
- time_t now = time(nullptr);
- while (now < 24 * 3600) {
- Serial.print(".");
- delay(100);
- now = time(nullptr);
- }
- Serial.println(now);
- // Set Adafruit IO's root CA
- client.setCACert(adafruitio_root_ca);
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //*********************************************[ Telegram Messages Function ]********************************************
- void handleNewMessages(int numNewMessages) {
- Serial.println("handleNewMessages");
- Serial.println(String(numNewMessages));
- for (int i = 0; i < numNewMessages; i++) {
- String chat_id = bot.messages[i].chat_id;
- String text = bot.messages[i].text;
- String from_name = bot.messages[i].from_name;
- if (from_name == "")
- from_name = "Guest";
- // Find position of ',' and '='
- int posA = text.indexOf("a=");
- int posB = text.indexOf("b=");
- if (posA != -1 && posB != -1) {
- // Extract values of a and b
- String value1String = text.substring(posA + 2, posB - 1);
- String value2String = text.substring(posB + 2);
- // Convert string values to integers
- value1 = value1String.toFloat();
- value2 = value2String.toFloat();
- }
- // Print extracted values for debugging
- Serial.print("Value of a: ");
- Serial.println(value1);
- Serial.print("Value of b: ");
- Serial.println(value2);
- if (text == "/send_test_action") {
- bot.sendChatAction(chat_id, "typing");
- delay(4000);
- bot.sendMessage(chat_id, "Did you see the action message?");
- }
- if (text == "/start") {
- String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
- welcome += "This is Chat Action Bot example.\n\n";
- welcome += "/send_test_action : to send test chat action message\n";
- bot.sendMessage(chat_id, welcome);
- }
- }
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //******************************************[ Handel Telegram Messages Function ]****************************************
- void ReceiveMessageFromTelegram() {
- if (millis() - bot_lasttime > 1000) {
- int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
- while (numNewMessages) {
- Serial.println("got response");
- handleNewMessages(numNewMessages);
- numNewMessages = bot.getUpdates(bot.last_message_received + 1);
- }
- bot_lasttime = millis();
- }
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //*************************************[ Read Ultrasonic Sensor Function ]***********************************************
- void ReadDistanceUsingUltrasonicSensor() {
- // Clears the trigPin
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- // Sets the trigPin on HIGH state for 10 micro seconds
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Reads the echoPin, returns the sound wave travel time in microseconds
- duration = pulseIn(echoPin, HIGH);
- // Calculate the distance
- distanceCm = duration * SOUND_SPEED / 2;
- // Convert to Volume
- // β Calibration Factor
- volume_cm3 = int((hight - (5 + distanceCm)) * 3.14 * radius * radius);
- waterLevel = map(distanceCm, 0, hight, 100, 0);
- // Prints the distance in the Serial Monitor
- Serial.print("Distance (cm): ");
- Serial.println(distanceCm);
- Serial.print("Volume (CM^3): ");
- Serial.println(volume_cm3);
- Serial.print("Water Level (%): ");
- Serial.println(waterLevel);
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //*******************************************[ Read Temprature Sensor Function ]*****************************************
- void ReadTempratureSensor() {
- sensors.requestTemperatures();
- temperatureC = sensors.getTempCByIndex(0);
- Serial.print("Temprature (ΒΊC): ");
- Serial.println(temperatureC);
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //******************************************[ Publish Data To Dashboard Function ]***************************************
- void Publish_Sensor_Data() {
- if (millis() - mqtt_lasttime > timeBetweenDataPointsToBeSent) {
- // Ensure the connection to the MQTT server is alive (this will make the first
- // connection and automatically reconnect when disconnected). See the MQTT_connect
- // function definition further below.
- MQTT_connect();
- // Publish distance to MQTT Server
- if (!distance_mqtt_Publish.publish(distanceCm)) {
- Serial.println(F("distance_mqtt_Publish: Failed"));
- } else {
- Serial.println(F("distance_mqtt_Publish: OK!"));
- }
- // Publish volume to MQTT Server
- if (!volume_mqtt_Publish.publish(volume_cm3)) {
- Serial.println(F("volume_mqtt_Publish: Failed"));
- } else {
- Serial.println(F("volume_mqtt_Publish: OK!"));
- }
- // Publish waterLevel to MQTT Server
- if (!waterLevel_mqtt_Publish.publish(waterLevel)) {
- Serial.println(F("waterLevel_mqtt_Publish: Failed"));
- } else {
- Serial.println(F("waterLevel_mqtt_Publish: OK!"));
- }
- // Publish Temprature to MQTT Server
- if (!temprature_mqtt_Publish.publish(temperatureC)) {
- Serial.println(F("temprature_mqtt_Publish: Failed"));
- } else {
- Serial.println(F("temprature_mqtt_Publish: OK!"));
- }
- // Publish TDS to MQTT Server
- if (!tds_mqtt_Publish.publish(tdsValue)) {
- Serial.println(F("tds_mqtt_Publish: Failed"));
- } else {
- Serial.println(F("tds_mqtt_Publish: OK!"));
- }
- mqtt_lasttime = millis();
- }
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
- //******************************************[ Re/Connect to MQTT Server Function ]***************************-***********
- void MQTT_connect() {
- int8_t ret;
- // Stop if already connected.
- if (mqtt.connected()) {
- return;
- }
- Serial.print("Connecting to MQTT... ");
- uint8_t retries = 3;
- while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
- Serial.println(mqtt.connectErrorString(ret));
- Serial.println("Retrying MQTT connection in 5 seconds...");
- mqtt.disconnect();
- delay(5000); // wait 5 seconds
- retries--;
- if (retries == 0) {
- // basically die and wait for WDT to reset me
- while (1);
- }
- }
- Serial.println("MQTT Connected!");
- }
- //***********************************************************************************************************************
- //***********************************************************************************************************************
Advertisement
Add Comment
Please, Sign In to add comment