#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
#define PIN_TRIG 3
#define PIN_ECHO 2
int pos = 0; // variable to store the servo position
void setup() {
Serial.begin(9600);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
digitalWrite(PIN_TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(PIN_TRIG, LOW);
// Read the result:
int duration = pulseIn(PIN_ECHO, HIGH);
int tiempo = map(duration, 117, 23527, 10, 100);
Serial.print("Distance in CM: ");
Serial.println(duration / 58);
Serial.print("Distance in inches: ");
Serial.println(duration / 148);
delay(1000);
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(tiempo); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(tiempo); // waits 15ms for the servo to reach the position
}
}