#include <Servo.h> // include the Servo library
Servo myservo; // create a servo object
// define the pins for Ultrasonic Sensor HC-SR04
const int trigPin = 9; // define the trigPin and trigPin for the Ultrasonic Sensor HC-SR04
const int echoPin = 10; // define the trigPin and echoPin for the Ultrasonic Sensor HC-SR04
void setup() {
myservo.attach(8); // attach the servo to pin 8
pinMode(trigPin, OUTPUT); // set the trigPin as an output
pinMode(echoPin, INPUT); // set the echoPin as an input
// start the serial communication
Serial.begin(9600);
}
void loop() {
long duration, distance; // create variables to store the duration and distance
digitalWrite(trigPin, LOW); // set the trigPin low
delayMicroseconds(2); // wait for 2 microseconds
digitalWrite(trigPin, HIGH); // set the trigPin high
delayMicroseconds(10); // wait for 10 microseconds
digitalWrite(trigPin, LOW); // set the trigPin low
duration = pulseIn(echoPin, HIGH); // read the duration of the pulse
distance = (duration/2) / 29.1; // calculate the distance in centimeters
if (distance < 100) { // if the distance is less than 20 cm
digitalWrite(8, LOW); // set the trigPin low
delay(1000); // wait for 1 second
digitalWrite(8, HIGH); // set the trigPin low
}
else { // if the distance is greater than 20 cm
digitalWrite(8, HIGH); // set the trigPin low
}
}