safwan092

Arduino Nano OLED 1.3 inch u8g lib Ultrasonic Sensor Water Level Simple With Buzzer no OLED Screen

Dec 1st, 2024
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 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 = 30;
  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. waterLevel = TANK_HEIGHT_CM - (distance + 5); //5cm for the gap between the water (when full) and the ultrasonic sensor
  47.  
  48. waterLevel = waterLevel + 10;
  49.  
  50.  
  51. percentFull = (waterLevel * 100) / TANK_HEIGHT_CM;
  52.  
  53.  
  54.  
  55. if (waterLevel < 1) {
  56. waterLevel = 0;
  57. }
  58.  
  59. if (percentFull < 1) {
  60. percentFull = 0;
  61. }
  62.  
  63. if (percentFull < 10) {
  64. digitalWrite(buzzerPin, HIGH);
  65. delay(2000);
  66. digitalWrite(buzzerPin, LOW);
  67. delay(1000);
  68. }
  69.  
  70. str = String(percentFull) + "%";
  71. Serial.println(percentFull);
  72. /*
  73. u8g2.clearBuffer(); // clear the internal memory
  74. u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
  75. u8g2.drawStr(0, 10, "Water Level:"); // write something to the internal memory
  76. u8g2.setFont(u8g2_font_ncenB18_tr); // choose a suitable font
  77. u8g2.drawStr(40, 40, str.c_str()); // write something to the internal memory
  78. u8g2.sendBuffer(); // transfer internal memory to the display
  79. */
  80. delay(1000);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment