#include <NewPing.h>
#include <Servo.h>
#define trigPin 13
#define echoPin 12
#define MAX_DISTANCE 500
int pinSpeaker = 10;
const int ledPin = 6;
NewPing sonar(trigPin, echoPin, MAX_DISTANCE);
int angle = 0;
Servo servo;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pinSpeaker, OUTPUT);
servo.attach(9);
// put your setup code here, to run once:
}
void loop() {
int duration, distance, pos = 0, i;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
Serial.print(distance);
Serial.println("cm");
if (distance <= 15){
digitalWrite(ledPin, HIGH);
for (angle = 0; angle < 180; angle++) {
servo.write(angle);
delay(15);
}
delay(5000);
if (distance >= 15);
digitalWrite(ledPin, LOW);
for (angle = 180; angle > 0; angle--) {
servo.write(angle);
delay(15);
}
delay(5000);
}
// put your main code here, to run repeatedly:
}