safwan092

Arduino Nano OLED 1.3 inch u8g lib Ultrasonic Sensor Water Level Simple

Nov 12th, 2024
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 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.  
  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(trigPin, OUTPUT);
  30. pinMode(echoPin, INPUT);
  31. Serial.begin(9600);
  32. }
  33. void loop(void) {
  34.  
  35. digitalWrite(trigPin, LOW);
  36. delayMicroseconds(2);
  37. digitalWrite(trigPin, HIGH);
  38. delayMicroseconds(10);
  39. digitalWrite(trigPin, LOW);
  40.  
  41.  
  42. duration = pulseIn(echoPin, HIGH);
  43. distance = duration * 0.034 / 2;
  44. waterLevel = TANK_HEIGHT_CM - (distance + 5); //5cm for the gap between the water (when full) and the ultrasonic sensor
  45.  
  46. waterLevel = waterLevel + 10;
  47.  
  48.  
  49. percentFull = (waterLevel * 100) / TANK_HEIGHT_CM;
  50.  
  51.  
  52.  
  53. if (waterLevel < 1) {
  54. waterLevel = 0;
  55. }
  56.  
  57. if (percentFull < 1) {
  58. percentFull = 0;
  59. }
  60.  
  61. str = String(percentFull) + "%";
  62. Serial.println(percentFull);
  63. u8g2.clearBuffer(); // clear the internal memory
  64. u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
  65. u8g2.drawStr(0, 10, "Water Level:"); // write something to the internal memory
  66. u8g2.setFont(u8g2_font_ncenB18_tr); // choose a suitable font
  67. u8g2.drawStr(40, 40, str.c_str()); // write something to the internal memory
  68. u8g2.sendBuffer(); // transfer internal memory to the display
  69. delay(1000);
  70. }
Advertisement
Add Comment
Please, Sign In to add comment