My Python bridge breaks every time the Arduino comes back as a different COM port
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?
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.
On Linux you’d just write a udev rule and get /dev/loadcell. On Windows it’s messier.
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.
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.
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.

