//defining pins
#define TRIGGER_1 2
#define ECHO_1 3
#define TRIGGER_2 4
#define ECHO_2 5
#define TRIGGER_3 6
#define ECHO_3 7
#define TRIGGER_4 8
#define ECHO_4 9
#define RED_LED_1 24
#define GREEN_LED_1 25
#define BLUE_LED_1 26
#define RED_LED_2 27
#define GREEN_LED_2 28
#define BLUE_LED_2 29
#define RED_LED_3 30
#define GREEN_LED_3 31
#define BLUE_LED_3 32
#define RED_LED_4 33
#define GREEN_LED_4 34
#define BLUE_LED_4 35
#define BUZZER 19
int getDistance(int triggerPin, int echoPin) {
long duration;
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2; //calculates the distance in meters
} //this function is to get the distance to the objects.
void setColor(int led, int red, int green, int blue) {
int redPin, greenPin, bluePin;
switch (led) {
case 1:
redPin = RED_LED_1;
greenPin = GREEN_LED_1;
bluePin = BLUE_LED_1;
break;
case 2:
redPin = RED_LED_2;
greenPin = GREEN_LED_2;
bluePin = BLUE_LED_2;
break;
case 3:
redPin = RED_LED_3;
greenPin = GREEN_LED_3;
bluePin = BLUE_LED_3;
break;
case 4:
redPin = RED_LED_4;
greenPin = GREEN_LED_4;
bluePin = BLUE_LED_4;
break;
}
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
} //this function is to set the color in RGB LEDs.
void setup() {
pinMode(TRIGGER_1, OUTPUT);
pinMode(ECHO_1, INPUT);
pinMode(TRIGGER_2, OUTPUT);
pinMode(ECHO_2, INPUT);
pinMode(TRIGGER_3, OUTPUT);
pinMode(ECHO_3, INPUT);
pinMode(TRIGGER_4, OUTPUT);
pinMode(ECHO_4, INPUT);
pinMode(RED_LED_1, OUTPUT);
pinMode(GREEN_LED_1, OUTPUT);
pinMode(BLUE_LED_1, OUTPUT);
pinMode(RED_LED_2, OUTPUT);
pinMode(GREEN_LED_2, OUTPUT);
pinMode(BLUE_LED_2, OUTPUT);
pinMode(RED_LED_3, OUTPUT);
pinMode(GREEN_LED_3, OUTPUT);
pinMode(BLUE_LED_3, OUTPUT);
pinMode(RED_LED_4, OUTPUT);
pinMode(GREEN_LED_4, OUTPUT);
pinMode(BLUE_LED_4, OUTPUT);
pinMode(BUZZER, OUTPUT);
Serial.begin(9600);
}
void loop() {
int distances[4];
distances[0] = getDistance(TRIGGER_1, ECHO_1);
distances[1] = getDistance(TRIGGER_2, ECHO_2);
distances[2] = getDistance(TRIGGER_3, ECHO_3);
distances[3] = getDistance(TRIGGER_4, ECHO_4);
for (int i = 0; i < 4; i++) {
if (distances[i] < 50) {
tone(BUZZER, 1000, 500);
setColor(i + 1, 255, 0, 0);
}
else if (distances[i] < 150) {
tone(BUZZER, 1000, 2000);
setColor(i + 1, 255, 165, 0);
}
else if (distances[i] < 300) {
tone(BUZZER, 1000, 1000);
setColor(i + 1, 0, 255, 0);
}
else {
noTone(BUZZER);
setColor(i + 1, 0, 0, 0);
}
}
delay(100);
}