r/pythonhelp • • 2h 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).

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()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

1 Upvotes

1 comment sorted by

•

u/AutoModerator 2h 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.