Servo Sweep Example

May 25, 2017

Overview

Sweeps the shaft of a  servo motor back and forth across 180 degrees.

This example makes use of the Arduino servo library.

Hardware Required

Circuit

Servo motors have three wires: power, ground, and signal. The power wire is typically red, and should be connected to the 5V pin on the Arduino or Genuino board. The ground wire is typically black or brown and should be connected to a ground pin on the board. The signal pin is typically yellow, orange or white and should be connected to pin 9 on the board.

click the images to enlarge

Schematic

Code

#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 
                // twelve servo objects can be created on most boards
void setup() 
{ 
  myservo.attach(2);  // attaches the servo on GIO2 to the servo object 
} 
void loop() 
{ 
  int pos;
  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>=0; 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 
  } 
} 

You can also download this code from: http://www.osoyoo.com/download/code/Servo_Sweep.zip

Leave a Reply

WordPress spam blocked by CleanTalk.
Bombax Theme designed by itx