// Define the pins for the ultrasonic sensor
const int trigPin = 3; // Trigger pin
const int echoPin = 2; // Echo pin
int red = 11;
int orange = 12;
int green = 13;
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT); // Set trigger pin as an OUTPUT
pinMode(echoPin, INPUT); // Set echo pin as an INPUT
pinMode(red, OUTPUT);
pinMode(orange, OUTPUT);
pinMode(green, OUTPUT);
}
void loop() {
// Trigger the ultrasonic sensor to send a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time taken for the pulse to return
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
// Speed of sound is approximately 343 meters per second
// Distance = (time * speed of sound) / 2
int distance = duration * 0.0343 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if(distance > 300)
{
digitalWrite(red,HIGH);
digitalWrite(orange,LOW);
digitalWrite(green,LOW);
}
else if(distance > 200 )
{
digitalWrite(red,LOW);
digitalWrite(orange,HIGH);
digitalWrite(green,LOW);
}
else
{
digitalWrite(red,LOW);
digitalWrite(orange,LOW);
digitalWrite(green,HIGH);
}
delay(100); // Wait for a moment before taking the next reading
}