0% found this document useful (0 votes)
12 views2 pages

Arduino Servo Control with Ultrasonic Sensor

Uploaded by

Mgm Mallikarjun
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)
12 views2 pages

Arduino Servo Control with Ultrasonic Sensor

Uploaded by

Mgm Mallikarjun
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>
// Declare the Servo pin
int servoPin = 3;
// Create a servo object
Servo Servo1;

// constants won't change


const int TRIG_PIN = 7; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = 6; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int RELAY_PIN = A5; // Arduino pin connected to Relay's pin
const int DISTANCE_THRESHOLD = 50; // centimeters

// variables will change:


float duration_us, distance_cm;

void setup()
{
[Link] (9600); // initialize serial port
[Link](servoPin);
pinMode(TRIG_PIN, OUTPUT); // set arduino pin to output mode
pinMode(ECHO_PIN, INPUT); // set arduino pin to input mode
pinMode(RELAY_PIN, OUTPUT); // set arduino pin to output mode
}

void loop()
{
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);

// measure duration of pulse from ECHO pin


duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;

if(distance_cm < DISTANCE_THRESHOLD)


{
digitalWrite(RELAY_PIN, HIGH); // turn on Relay

// Make servo go to 0 degrees


[Link](0);
delay(1000);
// Make servo go to 90 degrees
[Link](90);
delay(6000);
// Make servo go to 180 degrees
[Link](180);
//delay(1000);

delay(15000); // mgm
}
else
{
digitalWrite(RELAY_PIN, LOW); // turn off Relay
}
// print the value to Serial Monitor
[Link]("distance: ");
[Link](distance_cm);
[Link](" cm");

// delay(500); //
}

You might also like