Mi puente en Python se rompe cada vez que el Arduino vuelve como un puerto COM distinto
Traducido del English por IA ·
Estudiante, mi primer proyecto de IoT, perdón si es algo básico.En nuestro laboratorio, un Arduino Uno lee una celda de carga (HX711) e imprime una línea por segundo por USB. Una PC con Windows ejecuta mi script de Python con pyserial, que lee esas líneas y las envía por POST a la API HTTP de dispositivos de Hermetry con el token del dispositivo. Funciona, pero el script tiene serial.Serial("COM3", 9600) fijo en el código, y cada vez que alguien desconecta el Arduino y lo conecta a otro puerto USB, vuelve como COM7 o COM9 y el script falla con:
serial.serialutil.SerialException: could not open port 'COM3': FileNotFoundError
¿Puedo renombrar el puerto COM desde Python para que siempre sea COM3? ¿O puedo forzar a Windows a mantener ese número?
Student, first IoT project, sorry if this is basic.
In our lab an Arduino Uno reads a load cell (HX711) and prints one line per second over USB. A Windows PC runs my Python script with pyserial that reads those lines and POSTs them to Hermetry’s device HTTP API with the device token. It works, but the script has serial.Serial("COM3", 9600) hardcoded, and whenever someone unplugs the Arduino and plugs it into another USB port it comes back as COM7 or COM9 and the script dies with:
serial.serialutil.SerialException: could not open port 'COM3': FileNotFoundError
Can I rename the COM port from Python so it is always COM3? Or force Windows to keep the number?
Traducido del English por IA ·
Puedes fijarlo a mano en el Administrador de dispositivos, propiedades del puerto, Opciones avanzadas, Número de puerto COM. Pero eso es por cada conector USB, así que vuelve a cambiar en cuanto alguien use otro conector.
You can pin it by hand in Device Manager, port properties, Advanced, COM Port Number. But it’s per USB socket, so it comes back the moment someone uses another socket.
Traducido del English por IA ·
En Linux bastaría con escribir una regla udev y obtener /dev/loadcell. En Windows es más complicado.
On Linux you’d just write a udev rule and get /dev/loadcell. On Windows it’s messier.
Traducido del English por IA ·
Yo también soy principiante, pero el invierno pasado tuve exactamente esto con el PC de mi estación meteorológica, y la solución fue dejar de preocuparme por el número. Busca el puerto según lo que tiene conectado. pyserial puede listar los puertos con sus identificadores USB y su número de serie:
from serial.tools import list_ports
def find_arduino():
for p in list_ports.comports():
print(p.device, p.vid, p.pid, p.serial_number, p.description)
if p.vid == 0x2341 and p.serial_number == "85736323838351F0B0E1":
return p.device
return None
port = find_arduino()
ser = serial.Serial(port, 9600, timeout=2)
Ejecútalo una vez para imprimir los tuyos y copia el número de serie ahí. 0x2341 es el identificador de proveedor de las placas Arduino originales. Si la tuya es un clon con chip CH340 (vid 0x1A86), ten cuidado: esos normalmente no tienen número de serie, así que con dos clones no podrás distinguirlos y tendrías que identificarlos por p.location (el conector USB).Además, envuelve el bucle de lectura para que vuelva a buscar el puerto después de un error en lugar de morir, así la gente puede volver a conectar cuando quiera.
I’m a beginner too but I had exactly this with my weather station PC last winter, and the fix was to stop caring about the number. Find the port by what’s plugged into it instead. pyserial can list ports with their USB ids and serial number:
from serial.tools import list_ports
def find_arduino():
for p in list_ports.comports():
print(p.device, p.vid, p.pid, p.serial_number, p.description)
if p.vid == 0x2341 and p.serial_number == "85736323838351F0B0E1":
return p.device
return None
port = find_arduino()
ser = serial.Serial(port, 9600, timeout=2)
Run it once to print yours and copy the serial number in. 0x2341 is the vendor id of genuine Arduino boards. If yours is a clone with a CH340 chip (vid 0x1A86), careful: those usually have no serial number, so with two clones you can’t tell them apart and you’d match on p.location (the USB socket) instead.
Also wrap the read loop so it looks for the port again after an error instead of dying, then people can replug whenever they like.
Traducido del English por IA ·
Y guarda las lecturas en una lista mientras el puerto no está, y luego envíalas con su propio ts cuando vuelva. Si no, cada reconexión deja un hueco en el historial.
And keep the readings in a list while the port is gone, then send them with their own ts once it’s back. Otherwise every replug leaves a hole in the history.
Traducido del English por IA ·
Uno original, así que el número de serie funcionó. El script ahora lo encuentra en cualquier socket, y añadí el bucle de reconexión. Banerjee, ahora envío los datos almacenados en búfer como un array con ts, y se llenó el hueco de la reconexión de esta mañana.
Genuine Uno, so the serial number worked. Script now finds it on any socket, and I added the reconnect loop. Banerjee, I’m sending the buffered ones as an array with ts now, the gap from this morning’s replug filled in.
- Debes estar registrado para responder a este debate.
Únete a la conversación
Inicia sesión para preguntar y responder, dar me gusta a las publicaciones útiles y marcar la respuesta que resolvió tu problema. Cada aportación suma puntos y niveles.

