Search code examples
pythonserial-portpyserial

When to flush Pyserial buffers?


I am working with Pyserial and have a question regarding best practices surrounding flushing the input and output buffers. Currently I reset the output buffer before sending a command and reset the input before reading the reply. It seems I occasionally miss the start of a reply so I am considering modifying my program to reset the input buffer before I send my command. I am also considering linking my send and receive functions so that the send always calls the receive and hopefully tightens up the loop.

    def send_cmd(self, cmd_to_send):
        self.ser.reset_output_buffer()
        self.ser.write(cmd_to_send)

    def receive_cmd(self):
        self.ser.reset_input_buffer()
        # Read logic below

Considering transitioning to something like this

    def send_cmd(self, cmd_to_send):
        self.ser.reset_output_buffer()
        self.ser.reset_input_buffer()
        self.ser.write(cmd_to_send)
        self.receive_cmd()

    def receive_cmd(self):
        # Read logic below

Solution

  • This post gets decent traffic so I just want to let everyone know I never found the answer to this question. I tried a variety of configurations but ultimately flushing seems to rely more on the hardware itself than the software. I did end up transitioning to the code I mentioned and it seemed to help, albeit slightly. So I would recommend something like this:

    def send_cmd(self, cmd_to_send):
        self.ser.reset_output_buffer()
        self.ser.reset_input_buffer()
        self.ser.write(cmd_to_send)
        self.receive_cmd()
    
    def receive_cmd(self):
        # Read logic below
    

    If anyone can supply a better answer, I would still appreciate it :)

    Edit: I also was reading bytes individually, as I needed to. You may have more success using readlines() as Eduardo mentioned in the other answer.