Hello to everyone.
I'm trying to control a servo motor having an Arduino Uno connected to a USB port of my laptop.
I can actually move it, but not consistently, not all the commands are executed.
My concern is about the communication speed, but I cannot understand how to fix it.
At the moment I'm trying with some simple code that I post down below.
Python code
import serial
from time import sleep
arduino = serial.Serial('COM3', 115200, timeout=0.5)
sleep(5)
angles = [25, 40, -15, 80, -30, 10, 70, 0, -60, 0, -90]
for angle in angles:
command = str(angle)
arduino.write(bytes(str(angle), 'utf-8'))
sleep(1)
arduino.close()
Arduino code
#include <Servo.h>
Servo myservo;
String inByte;
int pos;
void setup() {
myservo.attach(8);
Serial.begin(115200);
myservo.write(90);
}
void loop() {
if(Serial.available()) {
inByte = Serial.readStringUntil('\n');
pos = inByte.toInt();
pos = 90+pos;
if(pos>=-90 && pos<=90) {
myservo.write(pos);
}
Serial.flush();
// already tried several values for the delay function
delay(15);
}
}
The servo motor is correctly initialized and positioned at 90°, the angles received must move the servo to the left or to the right.
The first 3 angles are always missed, the last 3 are almost always caught, the others are randomly caught or missed.
What is the correct method to have all the values processed?