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)