#include <Servo.h>
const int trigPin = 12;
const int echoPin = 14;
Servo myservo; // create servo object to control a servo
//define sound velocity in cm/uS
#define SOUND_VELOCITY 0.034
long duration;
float distanceCm;
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
myservo.attach(2); // attaches the servo on GIO2 to the servo object
}
void loop() {
getdistance();
if (distanceCm < 10){
rotateServo(100);
}
else{
rotateServo(10);
}
delay(100);
}
void getdistance() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_VELOCITY/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
delay(100);
}
void rotateServo(int pos){
myservo.write(pos);
delay(1000);
}