Reputation: 67
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)
Is this delay normal when using pySerial or is there something wrong with my code?
If delay in pySerial is usually seen, can you suggest a better library to read serial data?
Hacks tried:
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:
Appreciate your time.
Upvotes: 1
Views: 2820
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