#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const byte trig = 9;
const byte echo = 8;
const byte redPin = 11;
const byte greenPin = 10;
const byte bluePin = 6;
const byte switchPin = 2;
double distance, duration;
double lastDistance = -1; // Track the last measured distance
// Initialize LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(switchPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
lcd.begin(A4, A5);
lcd.backlight();
Serial.begin(115200);
}
void loop() {
// Check if the switch is ON
if (digitalRead(switchPin) == LOW) {
//ultrasonic sensor
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration = pulseIn(echo, HIGH);
distance = (duration * 0.0343) / 2;
//if the distance is not negative
// and different from the last recorded value
if (distance > 0 && distance != lastDistance) {
lastDistance = distance;
//distance on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance is:");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" cm");
// Control RGB LED based on distance
if (distance < 15) {
setColor(255, 0, 0); //red
} else if (distance < 30) {
setColor(0, 255, 0); // green
} else if (distance < 50) {
setColor(0, 0, 255); // blue
} else {
setColor(255, 255, 255); // white
}
}
} else {
// turn everything off if the switch isoff
setColor(0, 0, 0);
lcd.clear();
lastDistance = -1; // reset lastDistance
}
}
void setColor(int red, int green, int blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}