[go: up one dir, main page]

0% found this document useful (0 votes)
53 views1 page

Arduino Distance Sensor Guide

Uploaded by

elviswafula4529
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views1 page

Arduino Distance Sensor Guide

Uploaded by

elviswafula4529
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

#define trigPin 9

#define echoPin 8
#define ledPin 7

void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600); // Start Serial communication
}

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

// Read the echo pin


long duration = pulseIn(echoPin, HIGH);

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

Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

// Optional: Control LED based on distance


if (distance < 10) {
digitalWrite(ledPin, HIGH); // Turn LED on if distance < 10 cm
} else {
digitalWrite(ledPin, LOW); // Turn LED off otherwise
}

delay(500);
}

You might also like