Wurlitzer Wurlitzer - 2 months ago 9
Python Question

Precise timing with serial write

The code below sends a character over serial and waits 8 ms.

import serial
import time
from time import sleep

ser = serial.Serial(
port='/dev/cu.usbserial-AD01ST7I',\
writeTimeout = 0,\
baudrate=115200,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
)

for z in range(5000):
ser.write('C')
time.sleep(.008)


Measuring the serial activity on the serial port with a scope shows that the message is sent every ~10 ms. It varies a little – sometimes the interval is 8.5 ms.

Oscilloscope measurement

Is there a way to send the message precisely every 8ms?

Answer

No, unless you use RTOS. There are many factors that will affect the precision: