const int switchPin = 5;
const int triggerPin = 2;
const int echoPin = 4;
const int servoPin = 7;
const int controlPin = 6;
#include <Servo.h>
Servo myServo;
void setup() {
pinMode(triggerPin, OUTPUT); // define Arduino pin for trigger
pinMode(echoPin, INPUT); // define Arduino pin for echo
Serial.begin(9600); // enable serial monitor
pinMode(switchPin, INPUT);
myServo.attach(servoPin);
}
void loop() {
int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);
float y = voltage / 5;
// Send trigger pulse
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
long t = pulseIn(echoPin, HIGH); // input pulse and save it to variable
long inches = t / 74 / 2; // time convert distance to inches
long cm = t / 29 / 2; // time convert distance to cm
String inch = " inches";
String CM = " cm";
while (digitalRead(switchPin) == HIGH) {
float x = 90 * y;
float a = 90 - x;
float b = 90 + x;
for (int i=a;i<=b;i++) {
myServo.write(i);
delay(5);
Serial.print(inches);
Serial.print(inch);
Serial.print(" (");
Serial.print(cm);
Serial.print(CM);
Serial.println(")");
}
for (int i=b;i>=a;i--) {
myServo.write(i);
delay(5);
Serial.print(inches);
Serial.print(inch);
Serial.print(" (");
Serial.print(cm);
Serial.print(CM);
Serial.println(")");
}
}
if (digitalRead(controlPin) == HIGH) {
float c = 180 * y;
myServo.write(c);
Serial.print(inches);
Serial.print(inch);
Serial.print(" (");
Serial.print(cm);
Serial.print(CM);
Serial.println(")");
}
}