Controlling a servo with Arduino code

Controlling a servo motor with Arduino is much easier than you might think. You need just three wires, an Arduino and a servo. Following these steps you will have your servo running in minutes.

First of all, you will need to connect everything according to the following schematic. Hook up the yellow wire to pin 2, the red wire to the five Volt pin and the brown wire to GND.

Servo connection arduino

Now that we have hooked up all of the electronics, we’ll write our first piece of code. In this code block we include the servo library and declare some necessary variables.

// Include Servo library 
#include <Servo.h> 

// Declare the Servo pin 
int servoPin = 3; 
// Create a servo object 
Servo Servo1; 
void setup() { 
   // We need to attach the servo to the used pin number 

In the second piece of code, we tell the Arduino to change its angle by ninety degrees every second. You can obviously change the angles to any number you like.

void loop(){ 
   // Make servo go to 0 degrees 
   // Make servo go to 90 degrees 
   // Make servo go to 180 degrees 

After writing all of the code, upload it to the Arduino and you are ready to admire the servo’s work. If you want to get a servo yourself, you can try our project kit.

Leave a Reply