Stuttering Servo Motors

Hi,

Background

I’m building a simple, wheeled, obstacle avoiding Arduino robot. It consists of a wooden base with an Arduino Uno R3 and an Arduino sensor shield v.4.0 mounted on it. It’s powered by 4 AA batteries in a case. The servo motors are FS90R’s (plugged into 6 and 8 on the shield) and there is a Sharp GP2Y0A21YK0F Reflective (IR) distance Sensor mounted on the front.

Schematic

https://www.screencast.com/t/yvsozNTb

https://www.screencast.com/t/yvsozNTb

Code

#include <Servo.h>// Include servo library

Servo servoLeft; // Declare left servo
Servo servoRight; // Declare right servo

int IRpin = 0; // Analog pin for reading the IR sensor
float IRread; // Floating point number to hold converted voltage as distance

void setup() {
  servoLeft.attach(6); // Attach left signal to P6
  servoRight.attach(8); // Attach right signal to P8
}

void loop() {
  getDistance();

  if (IRread < 299) // NO OBSTACLE
  {
    forward();
  }

  else
  {
    dontGo();
  }
}
void getDistance() {
  IRread = analogRead(IRpin); // Reads the value of the sharp sensor
  delay(50);
}

void forward() { // Create a forward subroutine
  servoLeft.write(180);
  servoRight.write(25);
}

void dontGo() {
  servoLeft.write(90);
  servoRight.write(90);
}

void leftTurn() {
  servoLeft.write(90);
  servoRight.write(0);
}

Problem

The motors work fine without the IR distance sensor but when I add the IR distance sensor code the motors start and stop at very short time intervals with a stuttering motion.

I’ve tried using millis() as an alternative to delay() but the motors still stutter. Removing the delay() completely makes the motors stutter at really short intervals.

Any help or ideas would be much appreciated, please. Many thanks!

I think you may be updating the servo way too frequently. There’s no need to update them every 50ms. Try increasing the delay to a quarter or half second between readings. Also, try setting the delay to 1 second or so and printing out the IRRead value to see if it is noisy and 299 is right around the noise.

/mike

Thanks for your kind help.

I’ve tried increasing the delay as you suggested. The gap between the stutters increases accordingly but the stutters are still there.

I also set the delay to 1 second and printed out the IRRead values. I’m not sure what you mean by noisy, but the values were fairly random and varied between 240 and 150.

It appears to be switching between reading the IR value and driving the motors.

Any other thoughts or ideas would be appreciated.

Thanks again.