I wrote a Python script with pyserial to read data from two different USB devices (Witmotion IMU, Ublox ZED-F9P GNSS Receiver). This works perfectly on Windows. Every time I run the same script on a Raspberry Pi 4B (fresh Raspberry Pi OS) the whole Raspberry just freezes/crashes when trying to close the connection. So I can get data from the serial port and do whatever I want with it as long as I don't close the connection. Am I doing something wrong?
This is a minimal "working" example with that I can reproduce the crashes on any Raspberry 4B I have (tried it on 3 Raspberrys and on a VM running Raspberry Pi OS):
import threading
import serial
import time
def loop():
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200)
while run_event.is_set():
print("connected")
ser.close() # freeze
print("disconnected")
run_event = threading.Event()
run_event.set()
t = threading.Thread(target=loop)
t.setDaemon(True)
t.start()
time.sleep(10)
run_event.clear()
(Edit: Btw I get the same result if I do this without threading with some timer or limited number of loops:
import threading
import serial
import time
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200)
while i < 10:
print("connected")
time.sleep(1)
i = i+1
ser.close() # freeze
print("disconnected")
Note that it does only crash after stopping the connection. It also crashes when I just try to close the command line window while it still prints "connected".
I also noticed that I can make the Raspberry crash with the following command:
stty -F /dev/ttyUSB0 115200 -echo > /dev/null
Does anyone have some ideas on how to get the USB devices closed properly?
sudo journalctl
when you reboot, but note the time when the freeze occurs first, then leave the system on for a few minutes, then pull the plug, and corroborate this with timestamps in the journal to get a better sense of what is really going on; 2) When the freeze happens, try holding down alt+ctrl while you slowly cycle through F1 - F6 and see what happens (can't harm anything).