Hey y'all,
Working on a project to move a servo with an ultrasonic range finder (HC-SR04). I have movement, but it's repeated and I only want it to move once (from 00-1800-00). Any help is greatly appreciated. Thanks!
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED
#include <Servo.h>
Servo servo; // create servo object to control a servo
int pos =0;
int maximumRange = 100; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance
void setup() {
Serial.begin (9600);
servo.attach(2);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}
void loop() {
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
distance = duration/58.2;
if (distance >= maximumRange || distance <= minimumRange){
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
Serial.println("-1");
digitalWrite(LEDPin, LOW);
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
servo.write(pos); // tell servo to go to position in variable 'pos'
// waits 15ms for the servo to reach the position
}
for(pos = 99; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
servo.write(pos); // tell servo to go to position in variable 'pos'
delay (5); // waits 15ms for the servo to reach the position
}
}
else {
/* Send the distance to the computer using Serial protocol, and
turn LED OFF to indicate successful reading. */
Serial.println(distance);
digitalWrite(LEDPin, HIGH);
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
servo.write(pos); // tell servo to go to position in variable 'pos'
// waits 15ms for the servo to reach the position
}
for(pos = 99; pos>=1; pos-=1) // goes from 180 degrees to 0 degrees
{
servo.write(pos); // tell servo to go to position in variable 'pos'
delay(5); // waits 15ms for the servo to reach the position
}
}
//Delay 50ms before next reading.
delay(500);
}