#define sensors 3
const int trigPins[sensors] = {4, 6, 8};
const int echoPins[sensors] = {5, 7, 9};
const int l1 = 10; // LED pin
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(115200);
pinMode(l1, OUTPUT); // Initialize LED pin
for (int i = 0; i < sensors; i++) {
pinMode(trigPins[i], OUTPUT);
pinMode(echoPins[i], INPUT);
}
lcd.init();
lcd.backlight();
//Setup Awal Ketika Running
lcd.setCursor(2,0);
lcd.print("KELAS ALL TKJ");
lcd.setCursor(4,1);
lcd.print("SMK MUSKA");
delay(4000);
lcd.clear();
}
void loop() {
bool belowThreshold = false; // Flag for distance check
for (int i = 0; i < sensors; i++) {
long duration, distance;
// Trigger the sensor
digitalWrite(trigPins[i], LOW);
delayMicroseconds(2);
digitalWrite(trigPins[i], HIGH);
delayMicroseconds(10);
digitalWrite(trigPins[i], LOW);
// Measure the duration and calculate distance
duration = pulseIn(echoPins[i], HIGH);
distance = duration * 0.034 / 2; // Convert to cm
// Print sensor readings
Serial.print("Sensor ");
Serial.print(i + 1);
Serial.print(": ");
Serial.print(distance);
Serial.print(" cm");
// Check if the distance is below 100 cm
if (distance < 100) {
Serial.print(" <-- Distance below 100 cm");
belowThreshold = true; // Set flag to true
lcd.setCursor(2,0);
lcd.clear();
lcd.print("detect");
}
Serial.println();
}
// Set LED state based on sensor readings
if (belowThreshold) {
if (digitalRead(l1) == LOW) { // Change state only if needed
digitalWrite(l1, HIGH);
Serial.println("LED ON: Object detected within 100 cm!");
}
} else {
if (digitalRead(l1) == HIGH) { // Change state only if needed
digitalWrite(l1, LOW);
Serial.println("LED OFF: No object within 100 cm.");
lcd.clear();
lcd.print(("No detect"));
}
}
Serial.println();
delay(500);
}