Abstract123
Abstract123

Reputation: 67

Inconsistent delay in reading serial data in Python 3.7.2 using "PySerial"

I'm using pySerial library to read serial data from Arduino's basic example "AnalogReadSerial" into Python 3.7.2. There is an erratic delay of approx. 16 milliseconds and an unusual peak of approx. 1.5 seconds observed in every recording. (Printing time taken by Arduino is approx. 5 milliseconds/data point)

  1. Is this delay normal when using pySerial or is there something wrong with my code?

  2. If delay in pySerial is usually seen, can you suggest a better library to read serial data?

Hacks tried:

  1. I tried putting a sufficient delay in Arduino code (delay of 5ms) -- similar delay results.
  2. Suggestions in this thread -- PySerial delay in reading line from Arduino --incorporated "in_waiting"
  3. Took into account Arduino's printing time (approx. 5ms)
    import serial   
    import time 

    serialport = serial.Serial('COM3',9600)     #define my port 

    count =1          

    timedata = []

    while count<=100:                           #run for 100 serial values                

     if serialport.in_waiting > 0:              #buffer             

      count += 1                                
      t1 = int(round(time.time()*1000))         #time before reading   

      reading = serialport.readline().decode()  #read serial data and decode

      t2 = int(round(time.time()*1000))         #time after reading     

      finalt = t2 - t1                          #time taken to read             
      timedata.append(finalt)                   #store all time values in a list       
      print(timedata[-1])                       #print time for reading every new value     

I got similar results nearly every time. A peak of 1.5 seconds once during the code run and otherwise erratic 16ms delay.

Here is an image of the graph: Time taken (in milliseconds) to read 100 serial data points by python

Appreciate your time.

Upvotes: 1

Views: 2820

Answers (1)

IBNobody
IBNobody

Reputation: 46

You are likely running into this latency issue with your USB-to-Serial interface chip, which is likely an FTDI device.

https://projectgus.com/2011/10/notes-on-ftdi-latency-with-arduino/

On Linux & Windows, the default latency timer setting is 16ms. For example, say you send a 3 byte MIDI message from your Arduino at 115200bps. As serial data, it takes 0.3ms for the MIDI message to go from the Arduino’s microcontroller to the FTDI chip. However, the FTDI holds the message in its buffer for a further 15.8ms (16ms after the first byte arrived), before the latency timer expires and it sends a USB packet to the computer.

The article goes on to explain how to tweak your settings.

Upvotes: 3

Related Questions