Servo tiny random glitches

Hello,

I control a servo with the librairies in Arduino 16 with a SPDT switch and a led as a monitor. I am using a mini pro 3.3v for control and feeding the servo with a battery pack. The servo keeps doing tiny random glitches even if I detach it in the code. Previously I was using a more complicated code with a duemilanove and it was not doing any glitches. I really want to simplify the code and stop those anoying little BZZZT! ? I tried a pull-up resistor between pin 9 and 5v but it was worse... If someone has an idea !! I thank you for reading my msg.

New code :

int Switch1=2;
int val=0;
int Ledpin=13;

#include <Servo.h> 

Servo myservo;

void setup()
{ 
  pinMode(Switch1, INPUT);
  pinMode(Ledpin,OUTPUT);

} 

void loop() {
val = digitalRead(Switch1);
if (val == LOW){
        digitalWrite(Ledpin, LOW);
        myservo.attach(9);
        myservo.write(0);
        delay(500);
        myservo.detach();
        }
        else {
          digitalWrite(Ledpin, HIGH);
          myservo.attach(9);
          myservo.write(150);
          delay(500);
          myservo.detach();
          }
         
            
}

Old code:

int Switch1=2;
int val=0;
int Ledpin=13;
int buttonState = 0;
int servoPosition = 0;
#define servo1control OCR1A
#define servo1null 2000



void setup(){
 pinMode(Switch1, INPUT);
 pinMode(9,OUTPUT);
 pinMode(Ledpin,OUTPUT);
 TCCR1B = 0b00011010;
 TCCR1A = 0b10100010;
 ICR1 =  39999;
 servo1control = servo1null;
}

void loop(){
 val = digitalRead(Switch1);
 if (val == LOW) {
   if (buttonState == 0) {
     if (servoPosition == 0) {
       servo1control = 3750;
       digitalWrite(Ledpin, LOW);
       servoPosition = 1;
       delay(1000);
     }
     
     else {
       servo1control = 2200;
       digitalWrite(Ledpin, HIGH);
       servoPosition = 0;
       delay(1000);
     }
     buttonState = 1;
   }
 }
 
 else {
   buttonState = 0;
}
}

I'm having servo problems like this myself and have not been able to solve this after many many tests. However I'm using the MegaServo library to control 8 servos and much more code.

I see you are attaching the servo all the time in the loop. Why? You should only have to attach it once. Maybe that will solve the problem in your case.

EDIT: you should check the range of your servo as well. If your pulses are too short or to long the servo will go out of range and the motor will keep BZZZT-ing.... that seems a more logical cause as you're hering a continueous BZZZT whilst only updating the servo positing 2 every 500 ms.

I'm having servo problems like this myself and have not been able to solve this after many many tests. However I'm using the MegaServo library

See:
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1244582253/30#30