Serial port closes after first sending data when trying to control the servo motor

when i try to control a servo motor through an arduino connected to a computer using python code, after i send data for the first time, the motor turns, but the serial port closes and i have to restart the program, i have tried many variations, all i get is that the port just closes.
I mean if I make an infinite loop with constant requests for angle from the keyboard, the first time will control the servo motor, but when I enter the second value, the port closes and have to restart the program, please help me with the solution to this problem
arduino nano v3 on ATmega328PB and CH340C serial chip

And if I do it directly through arduino ide the motor works fine, for example if I make an infinite loop in which the motor spins from 0 to 180 and back again everything works fine

#include <Servo.h>

Servo myServo;

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

void loop() {
  if (Serial.available()) {
    String data = Serial.readStringUntil('\n');
    int angle = data.toInt();
    if (angle >= 0 && angle <= 180) {
      myServo.write(angle);
    }
  }
}
import serial
import time

port = 'COM10'
baudrate = 9600

ser = serial.Serial(port, baudrate, timeout=1)

try:
    for number in range(0, 181, 10):
        ser.write(f"{number}\n".encode())
        print(f"Sent: {number}")
        time.sleep(5)

This is one of many attempts to write code, I forgot to remove finally when I wrote this post, it was just a code test, of course, the code should be without explicitly closing the port in it. But I think I solved the problem, apparently I got a non-working serial chip on the arduino, tried it with another arduino and everything worked. Thanks

A try without finally or except? Not sure if the code runs this way...

Please provide a wiring diagram.
Is the servo powered by the Arduino? If yes moving it might cause a voltage drop and a reset of the Arduino.

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