/*
Controlling a servo position using a potentiometer (variable resistor)
by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>
modified on 8 Nov 2013
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/Knob
*/
//set names for connection of HC-SR04 -> Arduino pins
#define trigPin 10 //digital pin (read input + perform calc)
#define echoPin 13 //normal pin
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int val; // variable to read the value from the analog pin
float duration, distance;
void setup() {
pinMode(trigPin, OUTPUT); //sending pulses out from trigPin
pinMode(echoPin, INPUT); //recieving rebound pulse as I/P, to calc dist
myservo.attach(9); // attaches the servo on pin 9 to the servo object
myservo.write(0); //specifying initial speed and direction of servo
}
void loop() {
//manually sending 10us pulse
digitalWrite(trigPin, LOW); //starting LOW
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); //sending high part of pulse
delayMicroseconds(10);
digitalWrite(trigPin, LOW); //ending pulse
duration = pulseIn(echoPin, HIGH); //measures duration in which the Pulse stays high
distance = (duration/2) * 0.0343; //0.0343 cm/us is speed of sound
//val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
if(distance <= 10) {
myservo.write(180); //position of servo motor in degrees
delay(550); // waits for the servo to get there (1000us = 1s)
myservo.write(0);
delay(550); // waits for the servo to get there
}
}