Control an LED based on the range detected by an ultrasonic sensor

// Define pins
const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
const int ledPin = 13; // LED pin

void setup() {
pinMode(trigPin, OUTPUT); // Set trigPin as output
pinMode(echoPin, INPUT); // Set echoPin as input
pinMode(ledPin, OUTPUT); // Set LED pin as output
Serial.begin(9600); // Initialize serial communication
}

void loop() {
// Send a pulse to trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the pulse duration from the echo pin
long duration = pulseIn(echoPin, HIGH);

// Calculate the distance in cm
int distance = duration * 0.034 / 2;

// Print distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

// Control LED based on distance
if (distance > 0 && distance <= 20) { // Object within 20 cm
digitalWrite(ledPin, HIGH); // Turn on LED
} else {
digitalWrite(ledPin, LOW); // Turn off LED
}

delay(100); // Small delay for stability
}

Leave a Reply

Your email address will not be published. Required fields are marked *