Hi,
I’m using an ultrasonic sensor connected to a servo. The latter swings back and forth (from 10 to 130 degrees). When the distance between an object and the sensor is > 10 cm, the servo stops from swinging.
The following code works but the problem is that when the servo stops, it goes home to 0 degrees.
How to make the servo stop still?
TIA
int x = 1;
for (pos = 10; pos > -1; pos += x) { // goes from 10 degrees to 130 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
//delay(15); // waits 15ms for the servo to reach the position
ultrasound(); // take distance reading
if (dist > 10) break;
if (pos == 130) x = -1; // reverse direction
}
}
ok, here it is...
#include <Servo.h>
Servo myservo;
const int trigPin = 4; // (digital out) ultrasonic sensor
const int echoPin = 5; // (digital in) ultrasonic sensor
int ledPin = 13;
long dist, tmp; // ultrasonic calculated distance
int pos = 0; // servo position
void setup() {
Serial.begin(9600);
pinMode (trigPin, OUTPUT);
pinMode (echoPin, INPUT);
pinMode (ledPin, OUTPUT);
myservo.attach(6);
}
void loop() {
int x = 1;
for (pos = 10; pos > -1; pos += x) { // goes from 10 degrees to 130 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
//delay(15); // waits 15ms for the servo to reach the position
ultrasound(); // take distance reading
if (dist > 10) break;
if (pos == 130) x = -1; // reverse direction
}
}
void ultrasound () {
// set trigPin to LOW
digitalWrite (trigPin, LOW);
delay(10);
// Send out 8 pulses of 40k Hz
digitalWrite (trigPin, HIGH);
delay(10);
digitalWrite (trigPin, LOW);
tmp = pulseIn (echoPin, HIGH);
dist = tmp / 58;
}
Don't forget that loop is called repeatedly. Once your sensor notices something is further away than 10 and breaks out of your for loop, the loop function will be called again and pos will be 10 when you next command the servo. You need logic in loop that remembers what state your system is in from call to call.