safwan092

Nano Ultrasonic Water Level Simple With Buzzer Calibrated

Dec 3rd, 2024
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include <Arduino.h>
  2. //#include <U8g2lib.h>
  3. /*
  4. #ifdef U8X8_HAVE_HW_SPI
  5. #include <SPI.h>
  6. #endif
  7. #ifdef U8X8_HAVE_HW_I2C
  8. #include <Wire.h>
  9. #endif
  10. */
  11. const int buzzerPin = 4;
  12. const int trigPin = 9;
  13. const int echoPin = 10;
  14.  
  15. // Tank height in cm
  16. const int TANK_HEIGHT_CM = 20;
  17.  
  18. // Variables
  19. long duration;
  20. int distance;
  21. int waterLevel;
  22. int percentFull;
  23. String str;
  24.  
  25. //U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);
  26. void setup(void) {
  27.  
  28. //u8g2.begin();
  29. pinMode(buzzerPin, OUTPUT);
  30. pinMode(trigPin, OUTPUT);
  31. pinMode(echoPin, INPUT);
  32. digitalWrite(buzzerPin, LOW);
  33. Serial.begin(9600);
  34. }
  35. void loop(void) {
  36.  
  37. digitalWrite(trigPin, LOW);
  38. delayMicroseconds(2);
  39. digitalWrite(trigPin, HIGH);
  40. delayMicroseconds(10);
  41. digitalWrite(trigPin, LOW);
  42.  
  43.  
  44. duration = pulseIn(echoPin, HIGH);
  45. distance = duration * 0.034 / 2;
  46. Serial.print(distance);
  47. Serial.println("cm");
  48. waterLevel = TANK_HEIGHT_CM - (distance + 0); //5cm for the gap between the water (when full) and the ultrasonic sensor
  49.  
  50. waterLevel = waterLevel + 0;
  51. Serial.print(waterLevel);
  52. Serial.println("wL");
  53.  
  54. percentFull = (waterLevel * 100) / TANK_HEIGHT_CM;
  55.  
  56.  
  57.  
  58. if (waterLevel < 1) {
  59. waterLevel = 0;
  60. }
  61.  
  62. if (percentFull < 1) {
  63. percentFull = 0;
  64. }
  65.  
  66. if (percentFull < 10) {
  67. digitalWrite(buzzerPin, HIGH);
  68. delay(2000);
  69. digitalWrite(buzzerPin, LOW);
  70. delay(1000);
  71. }
  72.  
  73. str = String(percentFull) + "%";
  74. Serial.print(percentFull);
  75. Serial.println("%");
  76. /*
  77. u8g2.clearBuffer(); // clear the internal memory
  78. u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
  79. u8g2.drawStr(0, 10, "Water Level:"); // write something to the internal memory
  80. u8g2.setFont(u8g2_font_ncenB18_tr); // choose a suitable font
  81. u8g2.drawStr(40, 40, str.c_str()); // write something to the internal memory
  82. u8g2.sendBuffer(); // transfer internal memory to the display
  83. */
  84. delay(1000);
  85. }
Advertisement
Add Comment
Please, Sign In to add comment