[cpp] dfe

Viewer

  1. #include <NewPing.h>
  2. #include <LiquidCrystal_I2C.h> //memanggil library LCD
  3. #include <Servo.h> //memanggil library servo
  4.  
  5.  
  6. #define led1 6
  7. #define led2 7
  8.  
  9. LiquidCrystal_I2C lcd(0x27204);
  10. Servo servo;
  11.  
  12. const int trigPin1 = 9;
  13. const int echoPin1 = 10;
  14. const int trigPin2 = 11;
  15. const int echoPin2 = 12;
  16.  
  17. // Definisikan objek sensor ultrasonik dengan NewPing
  18. NewPing sonar1(trigPin1, echoPin1);
  19. NewPing sonar2(trigPin2, echoPin2);
  20.  
  21. int distanceHand;
  22. int distanceTrash;
  23. const int maxHeight = 100;
  24. String lastStatus = "Tertutup"; // Mengasumsikan posisi awal servo adalah tertutup
  25. int lastCapacityPercent = -1;    // Nilai awal kapasitas tong sampah belum di ketahui
  26.  
  27. void setup() {
  28.   servo.attach(3);
  29.   lcd.init();
  30.   lcd.backlight();
  31.   pinMode(led1, OUTPUT);
  32.   pinMode(led2, OUTPUT);
  33.   servo.write(0); // Pastikan servo dalam posisi tertutup pada awal
  34.   lcd.setCursor(00);
  35.   lcd.print("Status: Tertutup");
  36. }
  37.  
  38. void loop() {
  39.   distanceHand = sonar1.ping_cm();
  40.   String currentStatus = (servo.read() != 0) ? "Terbuka" : "Tertutup";
  41.  
  42.   // Deteksi tangan dan buka/tutup servo hanya jika perlu
  43.   if (distanceHand > 1 && distanceHand < 10 && currentStatus != "Terbuka") {
  44.     servo.write(90);
  45.     currentStatus = "Terbuka";
  46.   } else if ((distanceHand < 1 || distanceHand > 10) && currentStatus != "Tertutup") {
  47.     servo.write(0);
  48.     currentStatus = "Tertutup";
  49.   }
  50.  
  51.   distanceTrash = sonar2.ping_cm();
  52.   int capacityLeftPercent = calculateCapacity(distanceTrash);
  53.  
  54.   // Perbarui LCD hanya jika ada perubahan
  55.   if (currentStatus != lastStatus || lastCapacityPercent != capacityLeftPercent) {
  56.     lcd.clear();
  57.     lcd.setCursor(11);
  58.     lcd.print("Status:");
  59.     lcd.print(currentStatus);
  60.     lcd.setCursor(12);
  61.     if (capacityLeftPercent <= 20) {
  62.       lcd.print("Kapasitas: FULL");
  63.       digitalWrite(led1, LOW);
  64.       digitalWrite(led2, HIGH);
  65.     } else {
  66.       lcd.print("Kapasitas sisa:");
  67.       lcd.print(capacityLeftPercent);
  68.       lcd.print("%");
  69.       digitalWrite(led1, HIGH);
  70.       digitalWrite(led2, LOW);
  71.     }
  72.     lastStatus = currentStatus;
  73.     lastCapacityPercent = capacityLeftPercent;
  74.   }
  75.   delay(1000); // Kurangi atau sesuaikan delay ini sesuai kebutuhan
  76. }
  77.  
  78.  
  79. int calculateCapacity(int distance) {
  80.   int heightFilled = maxHeight - distance;
  81.   return 100 - ((heightFilled * 100) / maxHeight);
  82. }
  83.  

Editor

You can edit this paste and save as new:


File Description
  • dfe
  • Paste Code
  • 27 Apr-2024
  • 2.34 Kb
You can Share it: