Const Int Echopin

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

const int echoPin = 3; // Connect the ultrasonic sensor's echo pin to digital pin 3

const int ledPin = 13; // Connect the LED to digital pin 13

int distanceThreshold = 5; // Set the distance threshold for the LED to light up

void setup() {

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(ledPin, OUTPUT);

Serial.begin(9600); // Initialize serial communication for debugging

void loop() {

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

long duration = pulseIn(echoPin, HIGH);

float distance = duration * 0.034 / 2;

if (distance <= distanceThreshold && distance >= 0) {

digitalWrite(ledPin, HIGH); // Turn on the LED

} else {

digitalWrite(ledPin, LOW); // Turn off the LED

Serial.print("Distance: ");

Serial.print(distance);

Serial.println(" cm");

delay(500); // Delay for stability

You might also like