const int trigPin = 9; // Pin connected to the Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Pin connected to the Echo pin of the ultrasonic sensor
int led = 13; // Pin connected to the LED
float duration, distance; // Variables to store the duration and calculated distance
void setup() {
pinMode(trigPin, OUTPUT); // Set the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Set the echoPin as an INPUT
pinMode(led, OUTPUT); // Set the led pin as an OUTPUT
Serial.begin(9600); // Initialize serial communication at 9600 baud rate
}
void loop() {
// Clear the trigPin by setting it LOW for 2 microseconds
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance based on the speed of sound
distance = (duration * 0.0343) / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// If the distance is less than or equal to 50cm, turn the LED on, else turn it off
if (distance <= 50) {
digitalWrite(led, HIGH);
} else {
digitalWrite(led, LOW);
}
// Wait for 100 milliseconds before the next loop iteration
delay(100);
}