DIY Servo Motor: Cheap and with Plenty Muscle!

DC Motors can be made to turn either clockwise or counter-clockwise by changing the polarity of the voltage applied to their terminals. The torque that is generated at the output shaft can be scaled up or scaled down by using a gear train.

What is torque? In simple words, torque is a quantity that decribes the ‘strength’ of a motor. A motor torque of 50 kgcm means that lifting a 50kg weight at 1 cm could be achieved with that motor. By the law of moments, lifting 50 kg at a distance of 1 cm is equivalent to ……

Lifting 500 kg     at 0.1 cm
OR    Lifting 5 kg        at 10 cm
OR    Lifting 0.5 kg        at 100 cm

In most motors, like the one shown below, the gear train scales up the torque of the motor by using a reduction gearing that outputs a much higher torque (albeit at the cost of a much reduced output RPM).

Geared DC Motor

Geared DC Motor: This one generates 120kg-cm torque at 3.5 RPM

The problem with DC motors is that when they have a voltage applied to their terminals, they tend to rotate forever in a particular direction, stopping or reversing the motor can only be achieved by cutting off electric supply or reversing polarity.

In a DC Motor, speed control can be achieved by varying the terminal voltage but position control of the shaft is very difficult to implement.

Servo motors on the other hand, allow us to control the position (or angle) of the motor output shaft. This can be very useful when we want to move a control surface such as a rudder or a thruster to a particular position.

Servo Motors allow positional control

Servo Motors allow positional control

Servo motors are expensive. They get more and more expensive as their output torque increases. Digital servos are even more expensive than analog ones and I am not sure that one can even buy servo motors with torques higher than about 30 kg-cm. I have extrapolated the graph below (only analog servos) just to present a general idea about the costs of buying servo motors:-

Torque vs Cost of Commercially available servo motors

Torque vs Cost of Commercially available servo motors

I’m in the process of building a robotic arm. To make this work, I need ‘shoulder’ motors that can generate a torque of 120 kg-cm and I need to be able to control their position. In essence I need servo motors that generate 120 kg-cm of torque. From the graph above, it looks like I would need to shell out 600 US$ per motor!

So I decided to make these 120 kg-cm servo motors myself, and this is how I did it.

I used a geared DC motor that generates about 120 kg-cm of torque (when a 12 V DC voltage is applied to its terminals). This motor cost me about 14 US$.

Geared DC Motor

Geared DC Motor

For position control, I needed to be able to ‘encode’ the position of the shaft. This ‘current position’ would be compared against an ‘desired position’ and a ‘positional error’ would be generated. Voltage applied to the motor terminals would be so as to cause the shaft to turn to reduce ‘positional error’ to zero. This sort of a ‘feedback’ system is also used in commercially available servo motors.

Simple Feedback Loop

Simple Feedback Loop

To implement the feedback loop I fixed the shaft of a rotary potentiometer to the foundation of the motor while allowing the potentiometer’s body to rotate freely with the motor shaft. This arrangement is known as a shaft encoder. Now, as the motor shaft rotated, there would be a corresponding angular movement between the potentiometer shaft and its body. By sensing the voltage at the wiper terminal of the potentiometer, I could measure the angular position of the motor shaft. This angle would then be fed into the feedback loop allowing me to control the angular position of the motor shaft.

Shaft Encoder fixed onto the geared DC Motor

Shaft Encoder fixed onto the geared DC Motor

Here is the circuit diagram for the project. I made this with Fritzing.

DIY Servo Motor Circuit Diagram. Made with Fritzing

DIY Servo Motor Circuit Diagram. Made with Fritzing

The code to control the servo is given below. I use a rudimentary proportional control system to turn the motor shaft to the desired angle.

</pre>
<pre>//Arduino code to control angle of a motor shaft using a potentiometer for feedback
//Please use a low rpm motor. Not more than about 500 rpm.
//******POTENTIOMETER SETUP *************

//1. Fix the shaft of the potentiometer to the motor shaft.You might like to use a slightly flexible coupling
//to do this, otherwise even a slight misalignment may cause trouble.

//2. Fix the body of the potentiometer to a rigid surface such as the body of the motor,
//so that when the motor shaft turns, only the potentiometer shaft turns with it.

//3. Now we can read the potentiometer value to get the angle of the motor shaft

//Look at my youtube video to see how I did this. In my video, I fixed the BODY of the potentiometer
//to the motor shaft. It will be better to fix the SHAFT of the potentiomter to the motor
//shaft if you can do it properly

//Fix santa's hand to the motor shaft so that it does not interfere with the potentiometer movement

int potPin = 5; //we will read the potentiometer value on analog pin 5
//**********************************************

//*****ANGULAR CONSTANTS********

#define POT_VALUE_MAX 700 // potentiometer reading when motor shaft is at 180 degree position. 
//You will need to fill this value according to your setup.See below....

#define POT_VALUE_MIN 200//potentiometer reading when when motor shaft is at 0 degree position. 
//You will need to fill this value according to your setup.See below....

//To fill up the correct values, first turn the motor shaft manually to 0 degree position. 
//Now read the potentiometer value and edit the #define POT_VALUE_MIN line with your pot reading. 
//Next manually move the motor shaft to 180 degree position, 
//read the pot value and edit #define POT_VALUE_MAX line with your pot reading.

#define PERM_ERROR 3 //the max permissible error in degrees. In my potentiometer, a turn only about 3 degrees
//on the potentiometer shaft causes any real change in the ohmic reading. You can adjust this error
//value as required. If PERM_ERROR is very small, the shaft will keep hunting left and right as the
//analogRead() of the potentiometer pin keeps fluctuating slightly

#define MAX_ANGLE 180 //we will allow our motor to turn by a maximum angle of 180 degrees
//**********************************

//Now we define a class that will control our DC motor....
//This motor must be running from a H bridge like L298 IC

//********************************************************************
class DCMotor
{
private:

    int M_pin1 , M_pin2, M_PWMPin;

    int M_Speed;

    int turnDirection;
    
    enum turnDirection {right, left};

public:

    DCMotor(int p1, int p2, int p3) //Constructor
    {
            M_pin1 = p1; //direction pin on L298

            M_pin2 = p2;  //direction pin on L298

            M_PWMPin = p3;  //PWM pin on L298
            
            pinMode(M_pin1, OUTPUT);
            
            pinMode(M_pin2, OUTPUT);
    }

    void SetTurnDirection(int dir)//Setting turn directions on L298 IC
    {
        turnDirection = dir;

        switch(turnDirection)
        {
            case right: //turning Right

                    //motor moves CW

                    digitalWrite(M_pin1, HIGH);
                    digitalWrite(M_pin2, LOW);

                    break;

            case left: //turning Left

                    //motor moves CCW

                    digitalWrite(M_pin1, LOW);
                    digitalWrite(M_pin2, HIGH);

                	break;
        }
    }

    void SetTurnSpeed(int s)
    {
         M_Speed = s;
    }
    
    void Turn()
    {
        analogWrite(M_PWMPin, M_Speed);
    }
    
    void Stop()
    {
        analogWrite(M_PWMPin, 0);
    }
    
    void GoToAngle(int target, int howFast)
    {
      //find out the current angle of the motor shaft
  
      int currentAngle = ((float)analogRead(potPin) - POT_VALUE_MIN)/(POT_VALUE_MAX - POT_VALUE_MIN) * MAX_ANGLE;
      
      //First Check if we need to turn left or right.....
      if (currentAngle < target)
      {
        SetTurnDirection(right);
      } 
      else if (currentAngle > target)
      {
        SetTurnDirection(left);
      }
      
      SetTurnSpeed(howFast);
      
      while(abs(currentAngle - target) > PERM_ERROR)//if the shaft is not at the required value,
      {
        Turn();//Keep on turning the shaft
        
        //Allow the motor to turn a little and wait here for a moment...
        
        delay(100); //adjust the delay as required depending on your motor speed
        
        //update the current angle of the shaft 
        
        currentAngle = ((float)analogRead(potPin) - POT_VALUE_MIN)/(POT_VALUE_MAX - POT_VALUE_MIN) * MAX_ANGLE;
      } 
      
      Stop(); //Stop the shaft after the error is acceptable
    }

};

//DC Motor Class definition completed................
//************************************************************

//L298 pin defintions.....
int motor_p1 = 4;
int motor_p2 = 5;
int pwmPin = 9;


DCMotor customServo(motor_p1, motor_p2, pwmPin); //create an instance of the DC motor Class

//set the speed at which the motor will turn (Max speed = 255)
int turnSpeed = 200;

void setup()
{
  //no code is needed here for a simple up and down swing of santa's arm
}

void loop()
{
 
  //forwards turning..........
  for (int i = 30; i <= 150; i += 15) //our motor will turn from 30 to 150 degrees in steps of 15 degrees
  {
    customServo.GoToAngle(i, turnSpeed);
    
  }
  
  //backwards turning..........
  for (int i = 150; i >=30; i-=15)//now turn from 150 to 30 degrees in steps of 15 degrees
  {
    customServo.GoToAngle(i, turnSpeed);
    
  }
}</pre>
<pre>

The whole system works just fine. and best of all, its very very very cheap to implement! This has saved me hundreds of dollars I just could not afford to waste on commercially available servos, and hopefully this project will help me arrive at my final goal – the robotic human hand!

The DCMotor class can be downloaded from my github repo

Just download and copy into your arduino/libraries directory.

This youtube video demonstrates the project.

Advertisements

97 thoughts on “DIY Servo Motor: Cheap and with Plenty Muscle!

  1. Excellent post. I was checking continuously this blog and I am impressed! Extremely helpful information particularly the remaining section I take care of such info much. I used to be looking for this particular information for a very lengthy time. Thank you and best of luck.

  2. Really like it, good job! Quick question how did you manged to mount the potentiometer as I am thinking to do the same. Do you have any video tutorial where you can show how you did it. And one more thing, could you explain briefly where did you get all the numbers in your code. I am new in programming and need some help.

    • Thanks. I used thermoplastic and superglue (feviquick) to fix the potentiometer to the motor shaft. This was only a temporary arrangement, I now use a different technique. The pot body is fixed to the motor body with a long mechano piece bent to shape to which I screw the pot body in place. The pot shaft is fixed to the motor shaft using a semi-flexible plastic tube (I use motorcycle fuel tube). This couples the two shafts nicely and is flexible enough to absorb any vibrations. I will upload a photo of this soon.

      I have added comments to the numbers in the code, take a look. I hope this helps you out!

  3. Hey man, really nice job. Listen i have some questions to you about your project. I’m doing my self a project about drilling machine depth control and it’s kinda hard to find the right choice between price, torque, accuracy. Just one question how accurate is your dc motor?

    • In my project, position accuracy depends on the resolution of the potentiometer mounted on the motor shaft. I used the cheapest kind of pot available and find that it gives me a resolution of 3 – 4 degrees at best. Definitely not good enough for high precision work, but not bad at all, given the cost advantage.

  4. Sorry I forgot to describe the error displayed on my Arduino UNO it is:
    ‘DC Motor’ Does not name a type
    Let me tell you that I downloaded the Library named: BOMotor and it was added successfully into my Arduino Libraries.

    Thank you
    Darwin H

    • For this sketch, only dcmotor.h and dcmotor.cpp are needed. Both are available on my github repo. There is a link above. Sorry for the confusion, I will remove the part where I talk about the BOMotor class, I don’t think it is needed for this sketch at all.

  5. May I ask you a question? Can you explain a bit for me how can you connect potentiometer with your motor? I am in VN. and nowhere they sell the motor with potentiometer.
    and DCMotor motor1(42,43,2); ( the number 2 for what?)
    Thank you so much.

    • 1. I had to physically connect the shaft of the potentiometer to the motor. In this project I could not do this properly and compromised by fixing the pot body to the motor shaft with glue. After a lot of experimentation, I now connect the pot shaft and the motor shaft using semi-flexible tube. You need to do this yourself, because no one sells motor + pot attached.

      2. Pin 2 is any PWM pin that will connect to the Enable pin on the L298 H bridge

    • L293D Enable1—> Any Arduino PWM Pin
      L293D Input1—-> Any Arduino Digital Pin
      L293D Input2—–> Any Arduino Digital Pin

      L293D Output 1 & 2 —> DC Motor Terminals

      L293D Ground —-> Common Ground

  6. hi I cound not compile your code .Compilation errors as follows:
    sketch_jan14a.ino: In function ‘void ObeyServoOrder(double)’:
    sketch_jan14a.ino:51:37: error: ‘gt’ was not declared in this scope
    what should I do?

    • HI…I recently wrote some much better code to realise this algorithm. I have deleted all the old code and pasted in the new code into the blog. Please try that out and hopefully it will work just fine. Thanks for reading!

      • Hi there for some reason when I complile i get this error

        posicion.ino: In member function ‘void DCMotor::GoToAngle(int, int)’:
        posicion.ino:85:25: error: ‘lt’ was not declared in this scope
        posicion.ino:85:27: error: expected ‘)’ before ‘;’ token
        posicion.ino:85:35: error: expected ‘;’ before ‘)’ token
        posicion.ino:89:7: error: ‘else’ without a previous ‘if’
        posicion.ino:89:30: error: ‘gt’ was not declared in this scope
        posicion.ino:89:32: error: expected ‘)’ before ‘;’ token
        posicion.ino:89:40: error: expected ‘;’ before ‘)’ token
        posicion.ino:96:41: error: ‘gt’ was not declared in this scope
        posicion.ino:96:43: error: expected ‘)’ before ‘;’ token
        posicion.ino:96:55: error: expected ‘;’ before ‘)’ token
        posicion.ino: In function ‘void loop()’:
        posicion.ino:138:23: error: ‘lt’ was not declared in this scope
        posicion.ino:138:26: error: expected primary-expression before ‘=’ token
        posicion.ino:138:31: error: expected ‘)’ before ‘;’ token
        posicion.ino:138:33: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
        posicion.ino:138:33: note: (if you use ‘-fpermissive’ G++ will accept your code)
        posicion.ino:138:40: error: expected ‘;’ before ‘)’ token
        posicion.ino:145:24: error: ‘gt’ was not declared in this scope
        posicion.ino:145:27: error: expected primary-expression before ‘=’ token
        posicion.ino:145:30: error: expected ‘)’ before ‘;’ token
        posicion.ino:145:37: error: expected ‘;’ before ‘)’ token
        Error de compilación

        I already put the DCMotor Librarie and all the libraries from this link https://github.com/vu2aeo/Ard-Class
        But I still get erros
        Can you please help me.

      • This appears to be some sort of formatting error by the wordpress engine….lt is supposed to be the ” greater than symbol…please give me a day to fix this…I will do it ASAP.

        OK I have fixed the problem. The code is now self contained and does not need any external header/ source files.

  7. Hi, Great job and thanks for sharing. Have you considered an input to be a potentiometer instead of typing you can use a joystick to control the position.

  8. Hi. Can you explain the 119 line of your code (int currentAngle = (analogRead(potPin) – POT_VALUE_MIN)/POT_VALUE_MAX * MAX_ANGLE;). Why currentAngle is compute like that?
    Thank you for your reply.

    • analogRead(potPin) – POT_VALUE_MIN gives us the position of the shaft in terms of voltage reading. So if analogRead(potPin) – POT_MIN_VALUE = 0, then the shaft is at its minimum position.

      Now we divide this by POT_VALUE_MAX to give a shaft position as a fraction of maximum possible angular movement. So if this fraction = 0.3, it means we are 30 percent of the way from mimimum position to maximum position.

      Now multiply this by MAX_ANGLE to get the shaft position in degrees. So if we multiply 0.3 by MAX_ANGLE (suppose MAX_ANGLE = 180), then currentAngle = 0.3 * 180 = 60 degrees.

      Now the currentAngle can be compared with the desired angle (target) and the motor turned accordingly.

  9. hello my name is Mohammed of Morocco .I have à study project CNC milling machine with servo motor and encoders. can you help me to control this machine

  10. Hello, thank you for sharing your excellent works with us.
    I need help on a similar project. I have an Arduino Uno R3 and Sparkfun Monster Moto and two DC wiper motor with 10KOhm potentiometer.
    I want to control these motors by two potentiometer instead of PC keyboard.
    Could you help me about the Arduino codes and the wirings.
    Thank you in advance

    • Just read from the analog pin of each “controlling” potentiometer and then use the GoToAngle function to send the desired motor to the desired angle.

  11. hey , thank u so much for sharing this , i’m doing a project abour solar tracking system and i’m using dc motors .
    and i cound not compile your code . i get this msg ‘gt’ was not declared in this scope
    thnx for replying

  12. Hello man,
    Im making project about mine detecting robots, I got robot platform , Im controlling robot from computer ( C# application ) via bluetooth connection.I need to control position of the motors in the platform. For example I need to drive to platform 2mx2m area via button in C# application. I was thinking about hall effect sensor for position control but its not sensitive. How can I make this ? Can you help me please ?
    Burak Sevinc,
    Best regards

  13. Hello vu2aeo.. I’ll like to thank you for the awesome help you gave us to adapt your code to our project. The students were able to use your code from your “DIY Servo Motor- Cheap and with Plenty Muscle! ” and created a motorized turn table organizer that was powered by a DC motor and controlled via APP thru BT interface. The project was a success thanks to your expertise!!!!

    Here is the link to the video:

  14. Hi Aswan, Im trying to recreate this project using my ArduinoMega2560, I’ve downloaded the Arduino ver. 1.6.6, Installed, opened, the Arduino Mega board was selected, I’ve compiled/verified the sketch you have posted on your website with no issues, I downloaded the library Ard-DCMotor-class from github as a .zip, inserted on my Arduino Libray but there is an error message on my Arduino environment:

    Arduino: 1.6.6 (Windows 7), Board: “Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)”

    Sketch uses 3,424 bytes (1%) of program storage space. Maximum is 253,952 bytes.
    Global variables use 31 bytes (0%) of dynamic memory, leaving 8,161 bytes for local variables. Maximum is 8,192 bytes.
    Specified folder/zip file does not contain a valid library
    Invalid library found in C:\Program Files\Arduino\libraries\Ard-Class-master: C:\Program Files\Arduino\libraries\Ard-Class-master
    Invalid library found in C:\Program Files\Arduino\libraries\Ard-Class-master: C:\Program Files\Arduino\libraries\Ard-Class-master

    This report would have more information with
    “Show verbose output during compilation”
    enabled in File > Preferences.
    Please help me to find the problem. Thank you in advance.

  15. Hello! How can I set up for for Arduino Leonardo and L298N? I can not see anything in the serial monitor when I try to use this code … Thanks.

    • This code example does not use the serial input. The video is from an earlier project where I used serial input to order the servo motor.

      If you need to control the servo through serial input, you will need to modify the loop() function accordingly.

      First read from the serial input, storing the desired angle in a variable for example…. “a”.

      Now order the servo to follow this angle by using

      customServo.GoToAngle(a, turnSpeed);

    • ok, the code posted here has been modified slightly to make the servo arm swing back and forth automatically. If you want control from the serial interface, you will need to modify the loop() function accordingly. Just get a new desired angle using Serial.read() and then use GoToAngle(desired_angle, some_turn_speed) to obey that order

      • your making it seem too easy, if it was this easy i would have just done it ans not endup in your forum so when we watch a video on youtube and we have to leave youtube to come here only to find out that what you been showing us on the video is NOT what your supplying in the source provided is a big waste of time and quite disappointing sir,

      • what can i say…..if you’re not willing to put in any effort and expect everything to come prepackaged and tailor made to your requirements, you’re in for bigger disappointments in life.

        having said that, delete all the code in the loop() function and replace with the code below to implement control through serial interface…

        //Begin C++ code
        //dont forget to add Serial.begin(9600) line in the setup() function

        if(Serial.available())
        {
        int x = Serial.parseInt();
        customServo.GoToAngle(x, turnSpeed);
        }

        //End c++ code

        thanks for the feedback.

      • yeah see thats the point……your wasting my time and misleading me and others in watching something that does not relate to what your sharing so the bigger question is why would you do that, ?this types pf conversation is what you can expect in life when you pull someones leg, results are usually more painful in person but since this is the net your basically creating a troll

      • hmmmm….no leg pulling here my friend, theres plenty of people who have used this code to create their own custom servo motors. sure, it takes time and effort but thats what DIY is all about.

        anyway, i have posted some code for you to try. do that.

  16. Hi, I’m a 4th year honours student, my 4th year project (dissertation) is based on designing and building an electronic throttle control system for a small jet engine. I’m only starting out with programming and I’m a total beginner with Arduino so this has been a great help because it is exactly what I need for my project as servos with the desired torque output are out of budget, however my set up is slightly different and I’m wondering what changes (if any) would be required.

    I’m using an Arduino uno to control two individual motors (two different throttles ) through an Arduino motor shield deisgned to provide the 24v input, as a position sensor I am planning on using incremental quadrature rotary encoder as a method of positional feedback. Would there be any differences in the code for this?

    Also can you clarify how to download the code into the Arduino libraries.

    • Hi, glad to hear you found this work useful….

      1. I’m fairly certain this code will not work for more than one servo simultaneously. There would definitely need to be some major changes to the code to control two servos together. An easier cheat may be to use two smaller microcontrollers, perhaps like an AtTiny85, one for each servo. This might work quite nicely actually.

      2. Any type of feedback would work to control the servo. You would just need to tweak the code a little to read the angle value and then act on it.

      • Can you specify actually what type of tweaks would be required to read the angle from a incremental quadrature encoder?

      • I’ve managed to get this running but I would like to be able to control the position of the motor from the serial interface like you have done in the video. Can you post the exact code for me? Also do you have an available code you could post to control the motor with a linear potentiometer instead of using the keyboard or the serial interface?

      • Okay, I’ve also managed to use the serial interface but I’m having trouble actually controlling the motor. It will not home to an angle, whenever I give it a command it just drives until it reaches the stop point of the potentiometer and cannot move any further. I cant figure out the problem, any advice you could give?

    • you only need to find a way to mount the potentiometer so that it’s rigid attachment (to the motor body) doesnt interfere with whatever you are trying to turn. Some motors have a small shaft thats sticks out from the rear side. Attaching to this would be the easiest option I guesss. Or you would need some type of non-contact rotary encoder, optical would be the most suitable I think.

  17. Hi man i could not find this motor on aliexpress or amzaon can u give me a link to get it <>> plz help me because alot of motors the dont write the torque in descrbtion >>> ..
    give me more details PLZ ,,,

  18. From your code I have adapted something for sabertooth 2×25 but infortunatly it doesnt Work.
    May i Sent it to you for corrections ?

      • sabertooth 2 x 25 is a motor driver very easy to use. the arduino code is basically
        ST.motor ( motornumber, speed);
        motornumber is 1 or 2 and speed is from -127 to + 127
        in serialsimplified mode you only plug S1 to arduino 8 pin et GND to GND………………………

        here is the code. Thanks very much to have a look to it.
        Looking forward reading from you.

        #include
        #include
        #define POT_VALUE_MAX 700 // potentiometer reading when motor shaft is at 180 degree position. //You will need to fill this value according to your setup.See below….
        #define POT_VALUE_MIN 200//potentiometer reading when when motor shaft is at 0 degree position.
        #define PERM_ERROR 3
        #define MAX_ANGLE 180 //we will allow our motor to turn by a maximum angle of 180 degrees
        SoftwareSerial SWSerial(NOT_A_PIN, 8); //declare the Pin 8 to be used to communicate with Sabertooth
        SabertoothSimplified ST(SWSerial); //open a serial COM on previously identified pin

        int potPin = A0;
        int turnSpeed = 20;// from -127 to +127 with sabertooth
        char dir;
        int potPinval;

        //**********************************

        void SetTurnSpeed (int s )
        {
        turnSpeed = s;}

        void Turn ()
        {
        ST.motor ( 2,dir);}

        void Stop ()
        {
        ST.motor ( 2, 0);}

        void GoToAngle ( int target,int howFast)
        {
        int currentAngle = (( float)analogRead(potPin) – POT_VALUE_MIN)/(POT_VALUE_MAX – POT_VALUE_MIN) * MAX_ANGLE;

        if (currentAngle target)
        {
        dir = turnSpeed * -1;}

        SetTurnSpeed ( howFast);
        while(abs(currentAngle – target) > PERM_ERROR)//if the shaft is not at the required value,
        {
        Turn();//Keep on turning the shaft
        delay ( 50);
        //Allow the motor to turn a little and wait here for a moment…
        //adjust the delay as required depending on your motor speed
        //update the current angle of the shaft
        }
        Stop(); //Stop the shaft after the error is acceptable
        };
        //find out the current angle of the motor shaft

        void setup ()
        {
        Serial.begin ( 9600);
        }

        void loop ()
        {
        int currentAngle = (( float)analogRead(potPin) – POT_VALUE_MIN)/(POT_VALUE_MAX – POT_VALUE_MIN) * MAX_ANGLE;
        potPinval = analogRead ( potPin );
        Serial.println(“reglage 2 : “);
        Serial.println(potPinval);
        Serial.println(“reglage 1 : “);
        Serial.println(currentAngle );
        Serial.println(“dir : “);
        Serial.println(dir);

        for (int i = 30; i =30; i-=15)//now turn from 150 to 30 degrees in steps of 15 degrees
        {
        GoToAngle(i,dir);
        }

        }

      • Thank you for your code that is working now with Sabertooth motor driver ……only few changes were necessary.

  19. JE VOUS FELICITE TOUT D’ABORD POUR VOTRE PROJET D’ASSERVISSEMENT DE MOTEUR DC (DIT Y Servo Moteur ) ; ET J’AI L’HONNEUR DE VENNIR TRES RESPECTUEUSEMENT VOUS SOLICITER A M’AIDER DANS LA REALISATION D’un CNC
    (COUDEUSE DE FER A BETTON AUTOMATIQUE ) .
    j’AI PLACER UN ENCODER POUR MESURER LES DIMENSIONS DESIREES CELA FONCTIONNE TRES BIEN .
    ET AUSSI UN MOTEUR AC 2.2KW POUR FAIRE DES POSITIONS (ANGLES),
    JE COMMANDE LE MOTEUR PAR VARRIATURE DE FREQUENCE ET CELA FONCTIONNE AUSSI BIEN AVEC VOTRE CODE QUE J’ai TELECHARGER ET MODIFIER .
    DONC LES DEUX FONCTIONNENT SEPAREMENT NORMALEMMENT.
    MAIS ENSEMBLE SA NE MARCHERA PAS.
    MERCI POUR VOTRE ATTENTION.
    J’ATTEND VOTRE REPONCE.
    SALLUT.

    • Sorry I dont know french but as I understand you are using TWO motors. They are currently working independently but not together.

      Unfortunately, this code is not designed for TWO motors to work together so you may need to use 2 separate arduinos for your project.

  20. Excellent tutorial! But I think that Pot must be placed rotated at 180 degree, Then wires will be free from rotating.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s