Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <Arduino.h>
- //#include <U8g2lib.h>
- /*
- #ifdef U8X8_HAVE_HW_SPI
- #include <SPI.h>
- #endif
- #ifdef U8X8_HAVE_HW_I2C
- #include <Wire.h>
- #endif
- */
- const int buzzerPin = 4;
- const int trigPin = 9;
- const int echoPin = 10;
- // Tank height in cm
- const int TANK_HEIGHT_CM = 20;
- // Variables
- long duration;
- int distance;
- int waterLevel;
- int percentFull;
- String str;
- //U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);
- void setup(void) {
- //u8g2.begin();
- pinMode(buzzerPin, OUTPUT);
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- digitalWrite(buzzerPin, LOW);
- Serial.begin(9600);
- }
- void loop(void) {
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- duration = pulseIn(echoPin, HIGH);
- distance = duration * 0.034 / 2;
- Serial.print(distance);
- Serial.println("cm");
- waterLevel = TANK_HEIGHT_CM - (distance + 0); //5cm for the gap between the water (when full) and the ultrasonic sensor
- waterLevel = waterLevel + 0;
- Serial.print(waterLevel);
- Serial.println("wL");
- percentFull = (waterLevel * 100) / TANK_HEIGHT_CM;
- if (waterLevel < 1) {
- waterLevel = 0;
- }
- if (percentFull < 1) {
- percentFull = 0;
- }
- if (percentFull < 10) {
- digitalWrite(buzzerPin, HIGH);
- delay(2000);
- digitalWrite(buzzerPin, LOW);
- delay(1000);
- }
- str = String(percentFull) + "%";
- Serial.print(percentFull);
- Serial.println("%");
- /*
- u8g2.clearBuffer(); // clear the internal memory
- u8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable font
- u8g2.drawStr(0, 10, "Water Level:"); // write something to the internal memory
- u8g2.setFont(u8g2_font_ncenB18_tr); // choose a suitable font
- u8g2.drawStr(40, 40, str.c_str()); // write something to the internal memory
- u8g2.sendBuffer(); // transfer internal memory to the display
- */
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment