This circuit consists of an Arduino UNO microcontroller, a Servo motor, and an HC-SR04 Ultrasonic Sensor. The Arduino UNO controls the Servo motor based on the distance measured by the Ultrasonic Sensor. The sensor sends out ultrasonic waves and measures the time it takes for the echo to return, which is then used to calculate the distance to an object. If the object is within a certain range, the Servo motor is activated to perform a series of movements.
#include <Servo.h> //includes the servo library
Servo myservo;
#define echopin 2 // echo pin
#define trigpin 3 // Trigger pin
int set_cm = 50;
long ultra_time;
long dis_cm;
void setup(){ // put your setup code here, to run once
Serial.begin(9600);// initialize serial communication at 9600 bits per second:
myservo.attach(4);
myservo.write(0);
pinMode (trigpin, OUTPUT); // declare ultrasonic sensor Trigger pin as Output
pinMode (echopin, INPUT); // declare ultrasonic sensor Echo pin as input
delay(1000); // Waiting for a while
}
void loop(){
//*************************
ultra_read();
//*************************
Serial.print("Dis :");Serial.println(dis_cm);
if(dis_cm<set_cm){
myservo.write(20);
delay(50);
myservo.write(30);
delay(50);
myservo.write(40);
delay(50);
myservo.write(50);
delay(50);
myservo.write(80);
delay(50);
myservo.write(110);
delay(3000);
}
if(dis_cm>set_cm){
myservo.write(0);
}
delay(100);
}
//**********************ultra_read****************************
void ultra_read(){
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
ultra_time = pulseIn (echopin, HIGH);
dis_cm = ultra_time / 29 / 2;
}
This code initializes the Servo motor and the HC-SR04 Ultrasonic Sensor. In the setup
function, the Servo motor is attached to pin D4, and the ultrasonic sensor pins are set as input and output. The loop
function continuously reads the distance from the ultrasonic sensor and moves the Servo motor if the distance is less than a predefined value (set_cm
). The ultra_read
function handles the ultrasonic sensor reading and calculates the distance in centimeters.