// Include the Ultrasonic library
#include <Ultrasonic.h>
// Define pins for ultrasonic sensor
const int trigPin = 7;
const int echoPin = 6;
// Define pins for RGB LED
const int redPin = 11;
const int greenPin = 10;
const int bluePin = 9;
// Define distance thresholds for color changes
const int closeThreshold = 10; // Adjust as needed
const int farThreshold = 20; // Adjust as needed
// Initialize Ultrasonic object
Ultrasonic ultrasonic(trigPin, echoPin);
// Function prototype
void setColor(int redValue, int greenValue, int blueValue);
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set RGB LED pins as output
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// Set trigPin as output and echoPin as input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Read distance from ultrasonic sensor
int distance = ultrasonic.read();
// Control RGB LED based on distance
if (distance <= closeThreshold) {
// Close range: Turn on red
setColor(255, 0, 0);
} else if (distance <= farThreshold) {
// Medium range: Turn on green
setColor(0, 255, 0);
} else {
// Far range: Turn on blue
setColor(0, 0, 255);
}
// Output distance to serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
// Function to set RGB LED color
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}