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);
}
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 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()
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?