串行写入的精确定时
Precise timing with serial write
下面的代码通过串口发送一个字符并等待 8 毫秒。
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)
用示波器测量串行端口上的串行 activity 显示消息每 ~10 毫秒发送一次。它有一点变化——有时间隔是 8.5 毫秒。
有没有办法精确地每 8 毫秒发送一次消息?
否,除非你使用RTOS。影响精度的因素很多:
- 串行缓冲。您可以通过调用
flush
强制立即写入数据
- 计时器精度,每个 OS 都不同。有时以毫秒为单位。
- OS 调度,见https://en.wikipedia.org/wiki/Scheduling_(computing)
下面的代码通过串口发送一个字符并等待 8 毫秒。
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)
用示波器测量串行端口上的串行 activity 显示消息每 ~10 毫秒发送一次。它有一点变化——有时间隔是 8.5 毫秒。
有没有办法精确地每 8 毫秒发送一次消息?
否,除非你使用RTOS。影响精度的因素很多:
- 串行缓冲。您可以通过调用
flush
强制立即写入数据
- 计时器精度,每个 OS 都不同。有时以毫秒为单位。
- OS 调度,见https://en.wikipedia.org/wiki/Scheduling_(computing)