Precise timing with serial write
<p>The code below sends a character over serial and waits 8 ms.</p>

<pre><code>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)
</code></pre>

<p>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.</p>

<p><a href="http://i.stack.imgur.com/5Jycb.png" rel="nofollow">Oscilloscope measurement</a></p>

<p>Is there a way to send the message precisely every 8ms?</p>

<p><strong>No</strong>, unless you use <a href="https://en.wikipedia.org/wiki/Real-time_operating_system" rel="nofollow" title="RTOS">RTOS</a>. There are many factors that will affect the precision:</p>

<ul>
<li>Serial buffering. You can force to write the data immediately by calling <code>flush</code></li>
<li>Timer accuracy, which is different on each OS. Sometimes in the order of milliseconds. </li>
<li>OS scheduling, see <a href="https://en.wikipedia.org/wiki/Scheduling_(computing)" rel="nofollow">https://en.wikipedia.org/wiki/Scheduling_(computing)</a></li>
</ul>

python serial-port pyserial