safwan092

DR.Sahbi_Project_20-11-2024__Not_Tested_With_Water_Level

Nov 20th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.04 KB | None | 0 0
  1. //***********************************************************************************************************************
  2. //***********************************************[ Included Libraries ]**************************************************
  3. #include <WiFi.h>
  4. #include <WiFiClientSecure.h>
  5. #include <UniversalTelegramBot.h>
  6. #include "Adafruit_MQTT.h"
  7. #include "Adafruit_MQTT_Client.h"
  8. #include <ArduinoJson.h>
  9. #include <OneWire.h>
  10. #include <DallasTemperature.h>
  11. //***********************************************************************************************************************
  12. //***********************************************************************************************************************
  13. //**************************************************[ Pin Definitions ]**************************************************
  14. //Pump Relay Connections
  15. const int pumpRelayPin = 21;
  16. //TDS Sensor Connections
  17. const int TdsSensorPin = 34;
  18. //DS18B20 Sensor Connections
  19. const int oneWireBus = 4;
  20. //Ultrasonic Sensor Connections
  21. const int trigPin = 5;
  22. const int echoPin = 18;
  23. //***********************************************************************************************************************
  24. //***********************************************************************************************************************
  25. //**************************************************[ Web Dashboard Setup ]**********************************************
  26. /************************* WiFi Access Point *********************************/
  27. const char* ssid = "BS Home1";
  28. const char* password = "0554418546";
  29. /************************* Telegram Setup ************************************/
  30. #define BOTtoken "7231586324:AAFisXqDehD6vfX9hJ-8isgxaL0ALCqnMDk"
  31. #define CHAT_ID "985890015"
  32. /*********************** MQTT Account Setup **********************************/
  33. #define AIO_USERNAME "project19102024"
  34. #define AIO_KEY "aio_oONO288tq2G4GFfzGQTyhL3jaNUw"
  35.  
  36. #define AIO_SERVER "io.adafruit.com"
  37. // Using port 8883 for MQTTS
  38. #define AIO_SERVERPORT 8883
  39. // Adafruit IO Account Configuration
  40. // (to obtain these values, visit https://io.adafruit.com and click on Active Key)
  41. /************ Global State (you don't need to change this!) ******************/
  42. // WiFiFlientSecure for SSL/TLS support
  43. WiFiClientSecure client;
  44. // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
  45. Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
  46. // io.adafruit.com root CA
  47. const char* adafruitio_root_ca =
  48. "-----BEGIN CERTIFICATE-----\n"
  49. "MIIEjTCCA3WgAwIBAgIQDQd4KhM/xvmlcpbhMf/ReTANBgkqhkiG9w0BAQsFADBh\n"
  50. "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
  51. "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\n"
  52. "MjAeFw0xNzExMDIxMjIzMzdaFw0yNzExMDIxMjIzMzdaMGAxCzAJBgNVBAYTAlVT\n"
  53. "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
  54. "b20xHzAdBgNVBAMTFkdlb1RydXN0IFRMUyBSU0EgQ0EgRzEwggEiMA0GCSqGSIb3\n"
  55. "DQEBAQUAA4IBDwAwggEKAoIBAQC+F+jsvikKy/65LWEx/TMkCDIuWegh1Ngwvm4Q\n"
  56. "yISgP7oU5d79eoySG3vOhC3w/3jEMuipoH1fBtp7m0tTpsYbAhch4XA7rfuD6whU\n"
  57. "gajeErLVxoiWMPkC/DnUvbgi74BJmdBiuGHQSd7LwsuXpTEGG9fYXcbTVN5SATYq\n"
  58. "DfbexbYxTMwVJWoVb6lrBEgM3gBBqiiAiy800xu1Nq07JdCIQkBsNpFtZbIZhsDS\n"
  59. "fzlGWP4wEmBQ3O67c+ZXkFr2DcrXBEtHam80Gp2SNhou2U5U7UesDL/xgLK6/0d7\n"
  60. "6TnEVMSUVJkZ8VeZr+IUIlvoLrtjLbqugb0T3OYXW+CQU0kBAgMBAAGjggFAMIIB\n"
  61. "PDAdBgNVHQ4EFgQUlE/UXYvkpOKmgP792PkA76O+AlcwHwYDVR0jBBgwFoAUTiJU\n"
  62. "IBiV5uNu5g/6+rkS7QYXjzkwDgYDVR0PAQH/BAQDAgGGMB0GA1UdJQQWMBQGCCsG\n"
  63. "AQUFBwMBBggrBgEFBQcDAjASBgNVHRMBAf8ECDAGAQH/AgEAMDQGCCsGAQUFBwEB\n"
  64. "BCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEIGA1Ud\n"
  65. "HwQ7MDkwN6A1oDOGMWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEds\n"
  66. "b2JhbFJvb3RHMi5jcmwwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEW\n"
  67. "HGh0dHBzOi8vd3d3LmRpZ2ljZXJ0LmNvbS9DUFMwDQYJKoZIhvcNAQELBQADggEB\n"
  68. "AIIcBDqC6cWpyGUSXAjjAcYwsK4iiGF7KweG97i1RJz1kwZhRoo6orU1JtBYnjzB\n"
  69. "c4+/sXmnHJk3mlPyL1xuIAt9sMeC7+vreRIF5wFBC0MCN5sbHwhNN1JzKbifNeP5\n"
  70. "ozpZdQFmkCo+neBiKR6HqIA+LMTMCMMuv2khGGuPHmtDze4GmEGZtYLyF8EQpa5Y\n"
  71. "jPuV6k2Cr/N3XxFpT3hRpt/3usU/Zb9wfKPtWpoznZ4/44c1p9rzFcZYrWkj3A+7\n"
  72. "TNBJE0GmP2fhXhP1D/XVfIW/h0yCJGEiV9Glm/uGOa3DXHlmbAcxSyCRraG+ZBkA\n"
  73. "7h4SeM6Y8l/7MBRpPCz6l8Y=\n"
  74. "-----END CERTIFICATE-----\n";
  75. /****************************** Feeds ***************************************/
  76. //Data Rate Limit: The free account has a limit of 30 data points per minute
  77. //e.g. [5] Data points every [10] seconds gives [30] data points every [1 minute]
  78. //increasing interval between sending data points to avoid restriction on the account
  79. static unsigned long timeBetweenDataPointsToBeSent = 12000;
  80. Adafruit_MQTT_Publish distance_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/distance_mqtt");
  81. Adafruit_MQTT_Publish volume_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/volume_mqtt");
  82. Adafruit_MQTT_Publish waterLevel_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/waterLevel_mqtt");
  83. Adafruit_MQTT_Publish temprature_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temprature_mqtt");
  84. Adafruit_MQTT_Publish tds_mqtt_Publish = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/tds_mqtt");
  85. //***********************************************************************************************************************
  86. //***********************************************************************************************************************
  87. //******************************************[ Variables for TDS Sensor ]*************************************************
  88. #define VREF 3.3 // Reference voltage of ESP32 (3.3V for most ESP32 boards)
  89. #define ADC_RESOLUTION 4095 // 12-bit ADC resolution for ESP32
  90. float temperature = 25; // Temperature in Celsius, adjust as needed
  91. float calibrationFactor = 2; // TDS calibration factor (default 0.5 for most sensors)
  92. //86 ppm
  93. int analogValueTDS;
  94. float voltageTDS;
  95. float tdsValue;
  96. //***********************************************************************************************************************
  97. //***********************************************************************************************************************
  98. //***********************************************[ Read TDS Sensor Function ]********************************************
  99. void ReadTDSSensor() {
  100. analogValueTDS = analogRead(TdsSensorPin); // Read analog value from sensor
  101. voltageTDS = analogValueTDS * VREF / ADC_RESOLUTION; // Convert to voltageTDS
  102. tdsValue = (voltageTDS / calibrationFactor) * 1000; // Calculate TDS in ppm
  103. tdsValue = tdsValue / (1.0 + 0.02 * (25 - 25.0)); // Temperature compensation
  104. Serial.println("-------------------------");
  105. Serial.print("TDS Value: ");
  106. Serial.print(tdsValue, 2);
  107. Serial.println(" ppm");
  108. Serial.println("-------------------------");
  109. }
  110. //***********************************************************************************************************************
  111. //***********************************************************************************************************************
  112. //**************************************************[ Telegram Setup ]***************************************************
  113. WiFiClientSecure Sclient;
  114. UniversalTelegramBot bot(BOTtoken, Sclient);
  115. unsigned long bot_lasttime;
  116. unsigned long mqtt_lasttime;
  117. bool Start = false;
  118. float value1 = 0;
  119. float value2 = 0;
  120. //***********************************************************************************************************************
  121. //***********************************************************************************************************************
  122. //******************************************[ Variables for Ultrasonic Sensor ]******************************************
  123. //define sound speed in cm/uS
  124. #define SOUND_SPEED 0.034
  125. float radius = 3; //half the diameter in [CM]
  126. float hight = 30; //hight of the container in [CM]
  127. long duration;
  128. float distanceCm;
  129. float volume_cm3;
  130. int waterLevel;
  131. //***********************************************************************************************************************
  132. //***********************************************************************************************************************
  133. //*****************************************[ Temprature Sensor Setup ]***************************************************
  134. OneWire oneWire(oneWireBus);
  135. DallasTemperature sensors(&oneWire);
  136. float temperatureC;
  137. //***********************************************************************************************************************
  138. //***********************************************************************************************************************
  139. //**************************************************[ Main Setup Function ]**********************************************
  140. void setup() {
  141. Serial.begin(115200);
  142. SetupSensors();
  143. pumpOFF();
  144. SetupWiFiandTelegramBot();
  145. bot.sendMessage(CHAT_ID, "ESP32 Started WokWi");
  146. }
  147. //***********************************************************************************************************************
  148. //***********************************************************************************************************************
  149. //**************************************************[ Main Loop Function ]***********************************************
  150. void loop() {
  151. ReadDistanceUsingUltrasonicSensor();
  152. ReceiveMessageFromTelegram();
  153. ReadTempratureSensor();
  154. Publish_Sensor_Data();
  155. ReadTDSSensor();
  156. if (distanceCm > hight && ) {
  157. pumpON();
  158. }
  159. //delay(500);
  160. }
  161. //***********************************************************************************************************************
  162. //***********************************************************************************************************************
  163. //*************************************************[ Setup Sensors Function ]********************************************
  164. void SetupSensors() {
  165. pinMode(pumpRelayPin, OUTPUT);
  166. pinMode(TdsSensorPin, INPUT);
  167. pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  168. pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  169. sensors.begin();
  170. }
  171. //***********************************************************************************************************************
  172. //***********************************************************************************************************************
  173. //*************************************************[ Pump Functions ]********************************************
  174. void pumpON() {
  175. digitalWrite(pumpRelayPin, 1);
  176. delay(500);
  177. }
  178. void pumpOFF() {
  179. digitalWrite(pumpRelayPin, 0);
  180. delay(500);
  181. }
  182. //***********************************************************************************************************************
  183. //***********************************************************************************************************************
  184. //**********************************************[ Setup WiFi and Telegram Function]**************************************
  185. void SetupWiFiandTelegramBot() {
  186. // Connect to Wi-Fi
  187. WiFi.mode(WIFI_STA);
  188. WiFi.begin(ssid, password);
  189. Sclient.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  190. while (WiFi.status() != WL_CONNECTED) {
  191. delay(1000);
  192. Serial.println("Wifi Connected..");
  193. }
  194. // Print ESP32 Local IP Address
  195. Serial.println(WiFi.localIP());
  196. Serial.print("Retrieving time: ");
  197. configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
  198. time_t now = time(nullptr);
  199. while (now < 24 * 3600) {
  200. Serial.print(".");
  201. delay(100);
  202. now = time(nullptr);
  203. }
  204. Serial.println(now);
  205. // Set Adafruit IO's root CA
  206. client.setCACert(adafruitio_root_ca);
  207. }
  208. //***********************************************************************************************************************
  209. //***********************************************************************************************************************
  210. //*********************************************[ Telegram Messages Function ]********************************************
  211. void handleNewMessages(int numNewMessages) {
  212. Serial.println("handleNewMessages");
  213. Serial.println(String(numNewMessages));
  214. for (int i = 0; i < numNewMessages; i++) {
  215. String chat_id = bot.messages[i].chat_id;
  216. String text = bot.messages[i].text;
  217. String from_name = bot.messages[i].from_name;
  218. if (from_name == "")
  219. from_name = "Guest";
  220. // Find position of ',' and '='
  221. int posA = text.indexOf("a=");
  222. int posB = text.indexOf("b=");
  223. if (posA != -1 && posB != -1) {
  224. // Extract values of a and b
  225. String value1String = text.substring(posA + 2, posB - 1);
  226. String value2String = text.substring(posB + 2);
  227. // Convert string values to integers
  228. value1 = value1String.toFloat();
  229. value2 = value2String.toFloat();
  230. }
  231. // Print extracted values for debugging
  232. Serial.print("Value of a: ");
  233. Serial.println(value1);
  234. Serial.print("Value of b: ");
  235. Serial.println(value2);
  236. if (text == "/send_test_action") {
  237. bot.sendChatAction(chat_id, "typing");
  238. delay(4000);
  239. bot.sendMessage(chat_id, "Did you see the action message?");
  240. }
  241. if (text == "/start") {
  242. String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
  243. welcome += "This is Chat Action Bot example.\n\n";
  244. welcome += "/send_test_action : to send test chat action message\n";
  245. bot.sendMessage(chat_id, welcome);
  246. }
  247. }
  248. }
  249. //***********************************************************************************************************************
  250. //***********************************************************************************************************************
  251. //******************************************[ Handel Telegram Messages Function ]****************************************
  252. void ReceiveMessageFromTelegram() {
  253. if (millis() - bot_lasttime > 1000) {
  254. int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  255. while (numNewMessages) {
  256. Serial.println("got response");
  257. handleNewMessages(numNewMessages);
  258. numNewMessages = bot.getUpdates(bot.last_message_received + 1);
  259. }
  260. bot_lasttime = millis();
  261. }
  262. }
  263. //***********************************************************************************************************************
  264. //***********************************************************************************************************************
  265. //*************************************[ Read Ultrasonic Sensor Function ]***********************************************
  266. void ReadDistanceUsingUltrasonicSensor() {
  267. // Clears the trigPin
  268. digitalWrite(trigPin, LOW);
  269. delayMicroseconds(2);
  270. // Sets the trigPin on HIGH state for 10 micro seconds
  271. digitalWrite(trigPin, HIGH);
  272. delayMicroseconds(10);
  273. digitalWrite(trigPin, LOW);
  274. // Reads the echoPin, returns the sound wave travel time in microseconds
  275. duration = pulseIn(echoPin, HIGH);
  276. // Calculate the distance
  277. distanceCm = duration * SOUND_SPEED / 2;
  278. // Convert to Volume
  279. // ↓ Calibration Factor
  280. volume_cm3 = int((hight - (5 + distanceCm)) * 3.14 * radius * radius);
  281.  
  282. waterLevel = map(distanceCm, 0, hight, 100, 0);
  283.  
  284. // Prints the distance in the Serial Monitor
  285. Serial.print("Distance (cm): ");
  286. Serial.println(distanceCm);
  287. Serial.print("Volume (CM^3): ");
  288. Serial.println(volume_cm3);
  289. Serial.print("Water Level (%): ");
  290. Serial.println(waterLevel);
  291. }
  292. //***********************************************************************************************************************
  293. //***********************************************************************************************************************
  294. //*******************************************[ Read Temprature Sensor Function ]*****************************************
  295. void ReadTempratureSensor() {
  296. sensors.requestTemperatures();
  297. temperatureC = sensors.getTempCByIndex(0);
  298. Serial.print("Temprature (ΒΊC): ");
  299. Serial.println(temperatureC);
  300. }
  301. //***********************************************************************************************************************
  302. //***********************************************************************************************************************
  303. //******************************************[ Publish Data To Dashboard Function ]***************************************
  304. void Publish_Sensor_Data() {
  305. if (millis() - mqtt_lasttime > timeBetweenDataPointsToBeSent) {
  306. // Ensure the connection to the MQTT server is alive (this will make the first
  307. // connection and automatically reconnect when disconnected). See the MQTT_connect
  308. // function definition further below.
  309. MQTT_connect();
  310. // Publish distance to MQTT Server
  311. if (!distance_mqtt_Publish.publish(distanceCm)) {
  312. Serial.println(F("distance_mqtt_Publish: Failed"));
  313. } else {
  314. Serial.println(F("distance_mqtt_Publish: OK!"));
  315. }
  316. // Publish volume to MQTT Server
  317. if (!volume_mqtt_Publish.publish(volume_cm3)) {
  318. Serial.println(F("volume_mqtt_Publish: Failed"));
  319. } else {
  320. Serial.println(F("volume_mqtt_Publish: OK!"));
  321. }
  322. // Publish waterLevel to MQTT Server
  323. if (!waterLevel_mqtt_Publish.publish(waterLevel)) {
  324. Serial.println(F("waterLevel_mqtt_Publish: Failed"));
  325. } else {
  326. Serial.println(F("waterLevel_mqtt_Publish: OK!"));
  327. }
  328. // Publish Temprature to MQTT Server
  329. if (!temprature_mqtt_Publish.publish(temperatureC)) {
  330. Serial.println(F("temprature_mqtt_Publish: Failed"));
  331. } else {
  332. Serial.println(F("temprature_mqtt_Publish: OK!"));
  333. }
  334. // Publish TDS to MQTT Server
  335. if (!tds_mqtt_Publish.publish(tdsValue)) {
  336. Serial.println(F("tds_mqtt_Publish: Failed"));
  337. } else {
  338. Serial.println(F("tds_mqtt_Publish: OK!"));
  339. }
  340. mqtt_lasttime = millis();
  341. }
  342. }
  343. //***********************************************************************************************************************
  344. //***********************************************************************************************************************
  345. //******************************************[ Re/Connect to MQTT Server Function ]***************************-***********
  346. void MQTT_connect() {
  347. int8_t ret;
  348. // Stop if already connected.
  349. if (mqtt.connected()) {
  350. return;
  351. }
  352. Serial.print("Connecting to MQTT... ");
  353. uint8_t retries = 3;
  354. while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
  355. Serial.println(mqtt.connectErrorString(ret));
  356. Serial.println("Retrying MQTT connection in 5 seconds...");
  357. mqtt.disconnect();
  358. delay(5000); // wait 5 seconds
  359. retries--;
  360. if (retries == 0) {
  361. // basically die and wait for WDT to reset me
  362. while (1);
  363. }
  364. }
  365. Serial.println("MQTT Connected!");
  366. }
  367. //***********************************************************************************************************************
  368. //***********************************************************************************************************************
Advertisement
Add Comment
Please, Sign In to add comment