Servo is bugging out

I'm working on a little ROV project and I bought a Towerpro MG995 servo to control the steering. For some reason randomly the servo turns round as far as possible and starts spazing out, turning +-5ish(I can manually cause this if I leave A0 floating). The servo shouldn't even turn this far because I've set in my sketch to only allow the servo to turn between 100 and 160. Its a big problem because this will break the steering mech in my car. I can't seem to figure out what is causing this. I've tried using the arduino's 5v line and an external 5v supply(and yes I remembered to connect the grounds! XD)
(btw this is my first arduino forum post. I am no longer a lurker!)

Arduino: Arduino Uno
Arduino IDE: 1.0
OS: Ubuntu Precise Pangolin

Thanks for any help you can throw my way!

Cheers!

#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 
 
int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin 
 
void setup() 
{ 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
} 
 
void loop() 
{ 
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023) 
  val = map(val, 0, 1023, 100, 160);     // scale it to use it with the servo (value between 0 and 180) 
  myservo.write(val);                  // sets the servo position according to the scaled value 
  Serial.println(val);                  // prints val to serial
  delay(15);                           // waits for the servo to get there 
}

I can't see your code on my iPad, but you don't mention how you are powering you servo, check the two links in my signature for some examples.

Duane B
rcarduino.blogspot.com

Hi, Divide and conquer:

If you run the Sweep example: http://arduino.cc/it/Tutorial/Sweep (restrict the amount of movement to meet your plan) does it run for a long time with no problem? If so, the servo/power is OK

If you send the potentiometer reading to the Serial Monitor and move the pot all around, does the reading ever jump suddenly? If so, maybe the pot is bad / noisy.

In your code that sends the servo data, check that the value is within the limits you want, and if not, use the last reading over again?