Ultrasonic Sensor with Servo Motor

Assembling the Ultrasonic and Servo Motor

 

Step 1:  Attach the ultrasonic sensor to your breadboard.

Step 2:  Connect the 5 volts of Servo motor to the VCC of Ultrasonic sensor

Step 3:  Connect the VCC of ultrasonic to 5 volts of the Arduino Uno

Step 4:  Connect the GND of Servo motor to the GND of Ultrasonic sensor

Step 5:  Connect the GND of ultrasonic to GND of the Arduino Uno.

Step 6:  Connect the Digital pins.

CODE

Change the pins, degrees, and distance if needed.

 

#include <Servo.h> 
int servoPin = 7;
Servo Servo1;
const int trigPin = 9;
const int echoPin = 8;
long duration;
int distance;
int safetyDistance;

void setup () {
pinMode (trigPin, OUTPUT);
pinMode (echoPin, INPUT);
Servo1.attach(servoPin);
Serial.begin (9600);
}

void ultrasonic_sensor(){
  digitalWrite (trigPin, LOW);
  delayMicroseconds (2);
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = duration * 0.034 / 2;
  safetyDistance = distance; 
}

void loop () {
      ultrasonic_sensor();
      Servo1.write(0);
      
      if (distance < 30)
          { Servo1.write(160);
          delay(1500);  
      }  
      else { 
          Servo1.write(0); 
      }
      Serial.println (distance);
}

Leave a Reply