#include <Servo.h> // including servo library

const int trigPin = 10; // setting ultrasonic sensor trigger to pin 10
const int echoPin = 11; // setting ultrasonic sesnor echo to pin 11
const int servoPin = 12; // setting servo to pin 12

long duration; // declaring duration as a large number
int distance; // declaring distance as an integer

Servo myServo;

void setup() {
  pinMode(trigPin, OUTPUT); // setting trigger pin to output to emit the waves
  pinMode(echoPin, INPUT); // setting echo pin to input to catch the bounce back waves
  Serial.begin(9600); // opening serial monital at 9600 baud rate
  myServo.attach(servoPin);
}

void loop() {
  for (int i = 15; i <= 165; i++) { // rotating servo motor from 15 to 165 degrees
    myServo.write(i); // moves servo to i angle
    delay(30);
    distance = calculateDistance(); // triggers the ultrasonic distance sensor

    Serial.print(i); // serial prints the current angle of the servo
    Serial.print(",");
    Serial.println(distance); // serial prints distance after the angle seperated by a comma
  }

  
  for (int i = 165; i >= 15; i--) { // rotating servo motor back from 165 to 15 degrees
    myServo.write(i); // moves servo to i angle
    delay(30);
    distance = calculateDistance(); // triggers the ultrasonic distance sensor

    Serial.print(i); // serial prints the current angle of the servo
    Serial.print(",");
    Serial.println(distance); // serial prints distance after the angle seperated by a comma
  }
}

int calculateDistance() { // controls the ultrasonic distance sensor
  digitalWrite(trigPin, LOW); // sets trigpin to 0 volts (off)
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); // turns on trig pin to trigger an ultrasonic pulse
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW); // sets trig pin to 0 volts (off)
  duration = pulseIn(echoPin, HIGH); // times how long the duration is for pulse to return to the echo pin 
  distance = duration * 0.034 / 2; // calulates the distance based off the echo pin duration

  if (distance > 200) distance = 200; // sets a 200 cm distance limit
  return distance;
}