r/pythonhelp • u/JazzlikeTwo18 • 5d ago
ESP32 serial communication issue with pyserial
I'm working on a small project where my ESP32 sends data to a Python script through serial communication (USB). I'm using vscode WSL2 and the usbipd driver to share the USBs to linux from my main OS windows. It seems there are issues with this driver.
Sometimes, when I start my Python script, it suddenly writes thousands of identical lines to my output file almost instantly. After that, everything works normally and I receive new data every second as expected.
Here is my python script
import serial
import time
ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200)
file_path = "output.txt"
ser.reset_input_buffer()
with open(file=file_path, mode="w", encoding="UTF-8") as file:
try:
while True:
if ser.in_waiting > 0:
serial_output = ser.readline()
serial_output_str = str(serial_output, 'UTF-8')
file.write(serial_output_str)
file.flush()
else:
time.sleep(0.01)
except KeyboardInterrupt:
print("Arrêt du programme, enregistrement du fichier.")
finally:
ser.close()
Thanks for the help
•
u/AutoModerator 5d ago
To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/TombKingSettra 2d ago
Could be buffered serial data or the ESP32 resetting when the port opens Try adding a short delay after opening the port then clear the input buffer Also log timestamps and raw bytes to check whether the duplicates are coming from the ESP32 or the USB/WSL connection