SG90 Servo motor Datasheet

First code

#include <Servo.h>
Servo myServo; //Declare the use of a servo named « myServo »
int servoPosition = 0; //Variable containing the desired position of the servo

void setup()
{
myServo.attach(9); //Servo connected to the DIGITAL 9 pin
myServo.write(servoPosition); //Servo commanded in its initial posisiton
}

void loop()
{
//Rotation in one direction
for(servoPosition = 0; servoPosition <= 180 ; servoPosition++)
{
myServo.write(servoPosition);
delay(15); //Short wait to allow the servo time to reach its position
}
//Rotation in the opposite direction
for(servoPosition = 180; servoPosition >= 0 ; servoPosition–)
{
myServo.write(servoPosition);
delay(15);
}
}

Second code

#include <Servo.h>

Servo myServo; //Declare the use of a servo named « myServo »
int servoPosition = 0; //Variable containing the desired position of the servo
const char AN_POTENTIOMETER = 0;

void setup()
{
myServo.attach(9); //Servo connected to the DIGITAL 9 pin
myServo.write(servoPosition); //Servo commanded in its initial posisiton
}

void loop()
{
servoPosition = analogRead(AN_POTENTIOMETER);
servoPosition = map(servoPosition, 0, 1023, 0, 180);
myServo.write(servoPosition);
delay(15);
}

Leave a Reply