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

Arduino Servo Control with Ultrasonic Sensor

The document contains an Arduino sketch that controls a servo motor based on distance measurements from an ultrasonic sensor. It initializes the servo and sets up the sensor pins, then continuously reads the distance and adjusts the servo position accordingly. If the measured distance is less than 20 cm, the servo moves to 90 degrees; otherwise, it returns to 0 degrees.

Uploaded by

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

Arduino Servo Control with Ultrasonic Sensor

The document contains an Arduino sketch that controls a servo motor based on distance measurements from an ultrasonic sensor. It initializes the servo and sets up the sensor pins, then continuously reads the distance and adjusts the servo position accordingly. If the measured distance is less than 20 cm, the servo moves to 90 degrees; otherwise, it returns to 0 degrees.

Uploaded by

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

#include <Servo.

h>
Servo myservo;

// Pin definitions
const int trigPin = 4;
const int echoPin = 3;

void setup() {
// Initialize Serial Monitor
[Link](9600);
[Link](9);
[Link](0);
delay(15);

// Set pin modes


pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
// Clear the trigPin
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 and calculate the distance


long duration = pulseIn(echoPin, HIGH);
float distance = (duration * 0.034) / 2; // Convert to cm

// Print the distance to the Serial Monitor


[Link]("Distance: ");
[Link](distance);
[Link](" cm");

if(distance < 20){


[Link](90);
delay(5000);
}
else{
[Link](0);
delay(15);
}
delay(500); // Wait for a short while before the next reading
}

You might also like