Trying to control a servo motor with Python over USB

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)
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'))


Arduino code

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

void setup() {

void loop() {    
  if(Serial.available()) { 
    inByte = Serial.readStringUntil('\n');
    pos = inByte.toInt();
    pos = 90+pos;

    if(pos>=-90 && pos<=90) {

    // already tried several values for the delay function

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?

Try moving the pos = 90+pos to AFTER the if statement.


I see my mistake, thank you.

Lose the flush(), lose the delay().

You will lose input otherwise.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.