Uno resets every time my Pi script opens /dev/ttyUSB0
Bit of a beginner so sorry if this is obvious. I have an Arduino Uno clone (CH340 chip) plugged into a Raspberry Pi with USB. The Uno counts pulses from my gas meter’s reed switch and prints a line every 10 s, and a Python script on the Pi reads the lines and sends them to Hermetry.
Problem: every time the Python script starts (and it gets restarted by cron if it crashes), the Uno resets. The pulse count goes back to 0 and the first few seconds of serial are lost. On the board in Hermetry I get these weird drops in the gas total.
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=2)
# Uno LED blinks, "boot" line comes in, count=0
I read it’s the DTR line. How do I turn DTR off on ttyUSB0 so the Pi stops resetting the Arduino?
Traducido del English por IA ·
La solución más fácil: no reinicies el script. Ejecútalo como servicio de systemd con Restart=always, abre el puerto una vez y nunca lo cierres.
Easiest fix: don’t restart the script. Run it as a systemd service with Restart=always, open the port once and never close it.
Traducido del English por IA ·
¿Qué es DTR? Tengo el mismo tipo de montaje para un contador de agua
What is DTR? I have the same kind of setup for a water meter
Traducido del English por IA ·
DTR es una de las antiguas líneas de control de módem. En el Uno pasa por un condensador de 100 nF hasta el pin de reset, para que el IDE pueda reiniciar la placa antes de cargar un programa. Cualquier programa que abra el puerto cambia DTR, y la placa se reinicia. Yo me peleé con esto en un contador de líneas en el trabajo el año pasado.Por el lado del software, dos cosas juntas:
stty -F /dev/ttyUSB0 -hupcl # don't drop DTR when the port closes
ser = serial.Serial()
ser.port = '/dev/ttyUSB0'
ser.baudrate = 9600
ser.timeout = 2
ser.dtr = False
ser.open()
Ojo: en Linux, el controlador puede seguir activando DTR un momento en la primera apertura tras el arranque, así que esto reduce los reinicios, pero no siempre los elimina.La solución segura es el hardware: un condensador de 10 µF entre RESET y GND en el Uno, con el negativo a GND. Eso absorbe el pulso de reset. Después tienes que quitarlo (o pulsar reset a mano en el momento adecuado) cuando subas un nuevo firmware.Y para las caídas en tu total: guarda también el conteo en la EEPROM cada pocos minutos, o haz que el Uno envíe un total acumulado desde que se flasheó en lugar de desde el arranque. Así, un reinicio te costará unos pocos pulsos, no todo el total.
DTR is one of the old modem control lines. On the Uno it goes through a 100 nF capacitor to the reset pin, so the IDE can reset the board before an upload. Any program that opens the port toggles DTR, so the board resets. I fought this on a line counter at work last year.
Software side, two things together:
stty -F /dev/ttyUSB0 -hupcl # don't drop DTR when the port closes
ser = serial.Serial()
ser.port = '/dev/ttyUSB0'
ser.baudrate = 9600
ser.timeout = 2
ser.dtr = False
ser.open()
Be warned that on Linux the driver may still raise DTR for a moment on the very first open after boot, so this reduces resets, it doesn’t always kill them.
The sure fix is hardware: a 10 µF capacitor between RESET and GND on the Uno, minus to GND. That swamps the reset pulse. You then have to pull it out (or press reset by hand at the right moment) when you upload new firmware.
And for the drops in your total: also keep the count in EEPROM every few minutes, or have the Uno send a running total since it was flashed instead of since boot. A reset then costs you a few pulses, not the whole total.
Traducido del English por IA ·
+1 a enviar un total. Si alguna vez necesitas el consumo por hora, la API de historial y los gráficos pueden calcularlo a partir del contador.
+1 on sending a total. If you ever need consumption per hour, the history API and charts can work it out from the counter.
Traducido del English por IA ·
Gracias James. Solo -hupcl no bastó, la primera apertura después de un reinicio seguía reiniciándolo, como dijiste. Puse el condensador de 10 µF (con una etiqueta en la placa que dice «quitar para cargar», eso ya lo aprendí por las malas) y los reinicios desaparecieron. También pasé el script a systemd, como sugirió twilson. Todo está estable ahora.
Thanks James. -hupcl alone wasn’t enough, the first open after a reboot still reset it, like you said. Put the 10 µF cap on (with a label on the board saying «remove to upload», learned that the hard way already) and the resets are gone. Also moved the script to systemd like twilson said. Total is stable now.
- 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.

