Hey there fellas:
I'm trying to make a simple 'robot' which consists of an ultrasonic sensor sitting on top of a servo.
The program is simple as well: Read the data from the sensor, move the servo accordingly.
The problem is my servo doesn't move fluently. It "hangs" a bit then moves to the new angle. It has a 1 second interval. I can also see this interval from the LED that is attached to the PING Ultrasonic Sensor. This effect also seen from the serial monitor. (The values go down continuously for a while and then they hang for a second.)
When i remove the data cable of the servo, everything goes back to normal flow.
Here's my code:
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
long pos = 0; // variable to store the servo position
int pingPin = 2;
int duration;
int dist;
void setup()
{
Serial.begin(9600);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
myservo.write(90); // tell servo to go to position in variable 'pos'
}
void loop()
{
dist = distanceCm();
Serial.print(duration);
Serial.print(" mapped: ");
Serial.print(dist);
Serial.println();
if (duration > 0) //avoid the 0 returns
{
myservo.write(dist);
delay(50);
}
}
int distanceCm()
{
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
delay(100);
return map(duration,150,2600,45,75);
}
Thanks for the help.