Python Arduino servo control

Python code

# servo control 15.12.2016

# 1) user set servo position in python
# 2) position is sent to arduino
# 3) arduino moves servo to position
# 4) arduino send confirmation message back to python
# 5) message is printed in python console

import serial                                           # import serial library
arduino = serial.Serial('/dev/cu.usbmodem1421', 9600)   # create serial object named arduino
while True:                                             # create loop

        command = str(input ("Servo position: "))       # query servo position
        arduino.write(command)                          # write position to serial port
        reachedPos = str(arduino.readline())            # read serial port for arduino echo
        print  reachedPos                               # print arduino echo to console

Arduino code

#include <Servo.h>
Servo myservo; 
String inByte;
int pos;

void setup() {
 
  myservo.attach(9);
  Serial.begin(9600);
}

void loop()
{    
  if(Serial.available())  // if data available in serial port
    { 
    inByte = Serial.readStringUntil('\n'); // read data until newline
    pos = inByte.toInt();   // change datatype from string to integer        
    myservo.write(pos);     // move servo
    Serial.print("Servo in position: ");  
    Serial.println(inByte);
    }
}

F8DILD1GZAD1A4D.MEDIUM.jpg

arduino code mod

#include <Servo.h>
Servo myservo1;   
Servo myservo2;   
String inByte;
int pos;
int whichservo = 1;      

void setup() {
 
  myservo1.attach(9);
  myservo2.attach(10);
  Serial.begin(9600);
}

void loop()
{    
  if(Serial.available())  // if data available in serial port
    { 
    inByte = Serial.readStringUntil('\n'); // read data until newline
    pos = inByte.toInt();   // change datatype from string to integer 
      if(whichservo == 1)   
        {       
        myservo1.write(pos);     // move servo
        Serial.print("Servo1 in position: ");  
        Serial.println(inByte);
        whichservo = 2;
        }
      else if(whichservo == 2)
        {       
        myservo2.write(pos);     // move servo
        Serial.print("Servo2 in position: ");  
        Serial.println(inByte);
        whichservo = 1;
        }  
    }
}

 

20 thoughts on “Python Arduino servo control

  1. Depends on what you want. Do you want to enter servo positions once in python and have the servos go to their respective positions or enter one servo position at a time. Anyway you will have to create two servo objects in arduino say myservo1 and myservo2.

    Like

    1. Actually, I have two servos and I need to enter the two servo position (different positions for both servos) in python accordingly servos should go to their respective position. In arduino I will create two servos namely myservo1 and my servo2. But what about in the python.what all should i need to do in python?

      Like

  2. How about this. I did not change the python code but rather the arduino code which i uploaded above under arduino code mod. It basically works like this: You enter a position in python. Arduino reads this and checks which servo to control. After controlling the first servo it sends a confirmation to python. You’re now ready to enter a new servo position that arduino reads and controls the other servo. There might be typos or errors since I can not check the system at the moment. Please let me know if it worked out as planned.

    Like

    1. Sir the got the idea. But am facing issues while writing the Arduino code. It will be great if you can share the Arduino code?

      Like

  3. As i said, look above. There are three codes on this page. The python code, the old arduino code and last the one I made for you (under arduino code mod). I must point out that I have had issues copying the code to arduino IDE with internet explorer but copying works fine with safari and chrome.

    Like

    1. okay I check out it is working. If I already knows both of the servo position, for one servo is this how i want to write the python code arduino.write(‘180’)
      but if i give like this the position exactly how can i do with both the servo position?
      if so in arduino code should i need to use Serial.parseInt()

      Like

      1. Could you please rephrase your question I don’t quite understand. It would also be helpful if you tried to explain in detail what you want to accomplish.

        Like

  4. instead of asking for the servo position from the user, if I already know the position in which both the servos need to be moved. what will be the code in both python and Arduino

    Like

    1. Hmm…never used (or heard of) that platform. Maybe you could try something like this:

      In python for
      – servo1 you type values between 1000 and 1180 (example arduino.write(1045) )
      – servo2 you type values between 2000 and 2180 (example arduino.write(2120) )

      In arduino

      You still read the serial port and convert the string to an integer.

      inByte = Serial.readStringUntil(‘\n’);
      pos = inByte.toInt();

      Then with an if loop you check if the integer (pos) is less than 2000 and you know it is the first servo. Then subtract 1000 to get 45 which will turn the first servo. If the integer is >2000 you know it is the second servo and you’ll subtract 2000 to get 120 and so on.

      Like

    1. From nowhere. At first the variable whichservo equals 1 and therefore when arduino reads the serial port and gets a value it will move the first servo (look at if-loop). It will also change the variable whichservo to 2. Next time arduino gets a value from serial port it will move the second servo (look at else if-loop). In this manner the user can input values in python one at a time and arduino will alternate between the two servos. It might not the be the prettiest piece of code but it should have solved NEETHUs problem.

      Like

  5. As far as I’m aware there is no difference in neither the code nor the physical connections. The difference between analog/digital should be inside the servo.

    Like

  6. It prints the current servo position in arduino to the serial monitor ex (Servo in position: 78 ) The user can see this. Since python listens to the serial port it will also print this “echo”. One might ask who cares if the servo moves to the desired position. Well it’s very useful for debugging purposes, that is if something goes wrong. Secondly I think this two-way communication is nice.

    Like

  7. How would the python and arduino codes change if instead of receiving an input from the user, my angle is stored in a variable ‘r’ that i want to send to the arduino directly or some other corresponding angle?
    The value of r is constantly changing from a live feed and accordingly i want to move my servo motor.
    please help

    Like

    1. In python I would only change [command = str(your_variable)]. So instead of taking what ever value user is giving, it would use the value from the live feed. I understand what you are trying to accomplish but since I don’t have any equipment set up, I won’t be able to test. I would assume that if your live feed comes from say a potentiometer you might end up with some timing issues and stuttering performance because of the back and forth communication between arduino and python.

      I’d suggest that after getting a working setup you remove the echoing from the code for better performance. Just a hunch. Good luck!

      Like

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s