Spin Around with Servo Motor SG90

Updated: May 5, 2020



Know it

A servo motor (like the SG90) is a motor that is easy to control and rotate using the Arduino. You just tell it at what to angle to rotate and it will rotate to exactly the angle!


The SG90 rotates between 0° and 180° with 90° in each direction with three wires attached: red(positive), brown(negative) and orange(signal).


A cool feature that servos have is that it goes back to its original movement and position even if you try to change both.


Wire it

For this circuit all you need is:

  • SG90 Servo Motor

  • Jumper wires

  • Arduino board and USB connector

Simple right? Let's do the circuit then:


Connections:

  • Arduino pin GND Brown servo wire

  • Arduino pin 5V Red servo wire

  • Arduino pin 6 Orange servo wire


Code it

This code will rotate the servo from angle 0° to 180° and come back from 180° to 0°.


Learn from this code how to set the servo to a certain degree and then add it to your project to take advantage of how easy your can control the servo.

Simply use myservo.write(ANGLE);


Now let's try the code!

/*     
Controlling and rotating a Servo    

Tutorial link: https://www.learn.voltaat.com/post/sg90-servo   

This is an Arduino sketch that goes from  0° to 180° and come back from 180° to 0° while waiting for 15 mill second between each degree.

Components Needed:   
1. SG90 Servo motor....x1

 */
 
#include <Servo.h> //include this library in the sketch
Servo myservo;

int pos = 0;    // variable to store the servo position
int servoPin = 9 ; // The pin that servo is connected to. Pin 9


// This routine run once
void setup() {
  myservo.attach(servoPin);  // attaches the servo on pin 9 to the servo object
}

// This routine loops forever
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 >= 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
  }
}