Arduino with servo

hi friend i am new bee. i have problem in servo programing.my connection of servo is as, i have connect control pin(yellow) to pin 9 with my arduino uno board. i have power my servo with arduino board is at 5v and GND. i have program to go from 0 to 180 forward at 20degree step and then after som time delay go from 180 to 0 reverse. but in actually my servo goes forward continuously 0to 180 without step, also it does not reverse back. for my program is like,

 

 

#include <Servo.h>
 
Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created
 
int pos = 0;    // variable to store the servo position
 
void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}
 
 
void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 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
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {                               
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

 

 

 

 

 

 

i have one another query, can i convert 12v to 5v via voltage regulator L7805CV.could u tell me what is its circuit diagram.

** When i used the above code**

 When i used the above code it worked fine for me.

And if you want the servo to move in 20 degree step

Replace this

for(pos = 0; pos < 180; pos += 1)

with

for(pos = 0; pos < 180; pos += 20)

and replace this

for(pos = 0; pos < 180; pos -= 1)

with

for(pos = 0; pos < 180; pos -= 20)

in the above code