Using pyhton to communicate with arduino to control 2 servo motors

Hello Everyone, I am new to Arduino and I got stuck at programing my arduino uno board. My task is to create an algorithm to track an object so I am using opencv in python environment for that purpose, and arduino to control the servos. My problem is that I am not able to write a code that would send the coordinates of the object from python program to arduino.
what I am trying in python is:

import serial
ser = serial.Serial("COM11", '9600', timeout=2)
Xposition = 90
Yposition = 90
while True:
  .... some code....
  if medium_x > center_x +40:
            Xposition += 2
            ser.write((str(Xposition) + 'a').encode('utf-8'))
           # time.sleep(0.03)
        if medium_x < center_x -40:
            Xposition -= 2
            ser.write((str(Xposition) + 'a').encode('utf-8'))
           # time.sleep(0.03)
        if y_medium > y_center -40:
            posY -= 2
            ser.write((str(posY) + 'a').encode('utf-8'))
        if x_medium < x_center -40:
            posY -= 2
            ser.write((str(posY) + 'a').encode('utf-8'))
        break

my arduino uno code is:

#include <Servo.h>
int posx = 0;
int posy = 0
int servoxypin = 5;
int servoyzpin = 6;

Servo servoxy;
Servo servoyz;

void setup(){

Serial.begin(9600);
servoxy.attach(servoxypin);
servoyz.attach(servoyzpin);

}

void loop() {
while (Serial.available() == 0){
}
posx = Serial.parseInt();
posy = Serial.parseInt();

servoxy.write(posx);
servoyz.write(posy);

}

Please help me out

This Simple Python - Arduino demo should help get you started.

The Python code should work on Windows if you edit it to use the Windows style of COM ports.

Also look at Serial Input Basics - simple reliable non-blocking ways to receive data.

...R

Have you tried sending commands from the serial monitor to the arduino as a test?

zoomkat:
Have you tried sending commands from the serial monitor to the arduino as a test?

Yes I tried and they are working well. I tried to develop a simple code in arduino that takes 2 inputs from user as an angle to move servo. And they work quite well!

You might look at what might be different between what is sent from python and what is sent by the serial monitor.

You can interface Python with Arduinos via USB serial easily using the compatible libraries: pySerialTransfer and SerialTransfer.h.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE’s Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.

Example Python Script:

from time import sleep
from pySerialTransfer import pySerialTransfer as txfer

if __name__ == '__main__':
    try:
        link = txfer.SerialTransfer('COM13')
        
        link.open()
        sleep(2) # allow some time for the Arduino to completely reset
    
        link.txBuff[0] = 'h'
        link.txBuff[1] = 'i'
        link.txBuff[2] = '\n'
        
        link.send(3)
        
        while not link.available():
            if link.status < 0:
                print('ERROR: {}'.format(link.status))
            
        print('Response received:')
        
        response = ''
        for index in range(link.bytesRead):
            response += chr(link.rxBuff[index])
        
        print(response)
        link.close()
        
    except KeyboardInterrupt:
        link.close()

Example Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  myTransfer.txBuff[0] = 'h';
  myTransfer.txBuff[1] = 'i';
  myTransfer.txBuff[2] = '\n';
  
  myTransfer.sendData(3);
  delay(100);

  if(myTransfer.available())
  {
    Serial.println("New Data");
    for(byte i = 0; i < myTransfer.bytesRead; i++)
      Serial.write(myTransfer.rxBuff[i]);
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");
    Serial.println(myTransfer.status);
  }
}

Thank you for your guidance.. I tried sending 2 different outputs from my python program to the arduino to control 2 servos but that is not working it just goes haywire and behaves abruptly. Should I send the output from python using two different serial objects created in python?

aayushlakkad: Should I send the output from python using two different serial objects created in python?

You only need one pySerialTransfer object to send data to your Arduino. Did you see my first reply?