int trigpin=9;
int echopin=10;
int ledpin1=4;
int ledpin2=5;
int ledpin3=6;
long duration;
int distance;
void setup() {
Serial.begin(9600);
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(ledpin1, OUTPUT);
pinMode(ledpin2, OUTPUT);
pinMode(ledpin3, OUTPUT);
}
void loop() {
digitalWrite(trigpin,LOW);
delayMicroseconds(2);
digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);
duration=pulseIn(echopin,HIGH);
distance= duration * 0.034/2;
Serial.println("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(50);
if (distance >= 20 && distance < 40 ) {
analogWrite(ledpin1, 255); // Red LED at full brightness
analogWrite(ledpin2, 0); // Green LED off
analogWrite(ledpin3, 0); // Blue LED off
} else if (distance >= 40 && distance < 60) {
analogWrite(ledpin1, 255); // Red LED off
analogWrite(ledpin2, 255); // Green LED at full brightness
analogWrite(ledpin3, 0); // Blue LED off
}
else if (distance > 60) {
analogWrite(ledpin1, 255); // Red LED off
analogWrite(ledpin2, 255); // Green LED at full brightness
analogWrite(ledpin3, 255); // Blue LED off
}
else {
analogWrite(ledpin1, 0); // Red LED off
analogWrite(ledpin2, 0); // Green LED off
analogWrite(ledpin3, 0); // Blue LED at full brightness
}
delay(500) ;
}