Arduino – Servo motor
We're going to learn how to run motor called Servo.
This Post explains how to control a servo from your computer using Arduino.
SG90 is one of most famous server motor when we use servo or learn how it works with Arduino.
Let's dive in! 🙂
Please see the following diagram carefully and make your own system just like it!
please note Servo motor has three wires.
They are black, red and yellow coloured wires normally, but some Servo motors have different wire colours.
Black(or Brown)-coloured wire should be connected to GND pin of Arduino. (Ground)
Red-coloured wire should be connected to 5V pin of Arduino. (Power)
Yellow(or Orange)-coloured wire should be connected to 7 pin of Arduino. (Signal)
As you can see, we've picked 7 pin to send signal to Arduino.
Let's take a look at Software side.
If anyone does not know 'How to upload our sketch to Arduino', then please click the following article before you go.
- Move Servo to various degrees
Step 1) Include the Servo library for controlling Servo motor
#include <Servo.h>
Step 2) Declare Servo pin we want to use with
int ServoPin = 7;
Step 3) Create Servo object to control a Servo
Servo MyServo;
Step 4) Attach the servo to the 7 pin
void setup()
{
MyServo.attach(ServoPin);
}
Step 5) Move Servo to 0, 45, 90, 135 and 180 degrees with 1 second delay
void loop()
{
MyServo.write(0);
delay(1000); // 0 degrees
MyServo.write(45);
delay(1000); // 45 degrees
MyServo.write(90);
delay(1000); // 90 degrees
MyServo.write(135);
delay(1000); // 135 degrees
MyServo.write(180);
delay(1000); // 180 degrees
}
- Practical Example : waving hand
Step 1) Include the Servo library for controlling Servo motor
#include <Servo.h>
Step 2) Declare Servo pin we want to use with
int ServoPin = 7;
Step 3) Create Servo object to control a Servo
Servo MyServo;
Step 4) Attach the servo to the 7 pin
void setup()
{
MyServo.attach(ServoPin);
}
Step 5) We just need to move Servo from 0 to 180 degrees and vice versa with very short delay
so that this action looks like waving hand. 🙂
void loop()
{
MyServo.write(180);
delay(600);
MyServo.write(0);
delay(600);
}
If you want to see it's moving quicker, use the following code.
void loop()
{
MyServo.write(180);
delay(300);
MyServo.write(0);
delay(300);
}
If you want to adjust the angle of waving hand, use the following code.
void loop()
{
MyServo.write(135);
delay(300);
MyServo.write(45);
delay(300);
}
How was it?
I believe you can be more smart or think about great idea to extend this.
You can do it! 🙂
Leave a Reply
Want to join the discussion?Feel free to contribute!