使用Python和pyparallel的方波

时间:2015-01-10 17:02:09

标签: python waveform

我想为外部设备生成方波时钟波形。

我在带有LPT1端口的旧PC上使用带有Windows 7 32位的python 2.7。 代码很简单:

import parallel
import time
p = parallel.Parallel()     # open LPT1
x=0
while (x==0):
    p.setData(0xFF)
    time.sleep(0.0005)
    p.setData(0x00)

我确实看到了方波(使用范围)但没有预期的时间段。

我会感激任何帮助

2 个答案:

答案 0 :(得分:0)

生成这样的信号很难。提到一个很难的原因可能是当超过睡眠时间时,过程会得到中断的回报。

发现这篇关于睡眠精确度的文章,其中包含一个很好的答案: How accurate is python's time.sleep()?

另一个信息来源:http://www.pythoncentral.io/pythons-time-sleep-pause-wait-sleep-stop-your-code/

信息告诉你的是,Windows能够至少休眠〜10ms,在Linux中时间约为1ms,但可能会有所不同。

更新 我的功能使睡眠时间少于10毫秒。但精确度非常粗略。

在附带的代码中,我包含了一个测试,它展示了精度的表现。如果您想要更高的精度,我强烈建议您阅读我在原始答案中附加的链接。

from time import time, sleep
import timeit


def timer_sleep(duration):
    """ timer_sleep() sleeps for a given duration in seconds
    """
    stop_time = time() + duration

    while (time() - stop_time) < 0:
        # throw in something that will take a little time to process.
        # According to measurements from the comments, it will take aprox
        # 2useconds to handle this one.
        sleep(0)


if __name__ == "__main__":
    for u_time in range(1, 100):
        u_constant = 1000000.0
        duration = u_time / u_constant

        result = timeit.timeit(stmt='timer_sleep({time})'.format(time=duration),
                               setup="from __main__ import timer_sleep",
                               number=1)
        print('===== RUN # {nr} ====='.format(nr=u_time))
        print('Returns after \t{time:.10f} seconds'.format(time=result))
        print('It should take\t{time:.10f} seconds'.format(time=duration))

快乐的黑客攻击

答案 1 :(得分:0)

它提供了一段时间的预期表现......继续减少时间

import parallel
import time
x=0
while (x<2000):
    p = parallel.Parallel()
    time.sleep(0.01)     # open LPT1
    p.setData(0xFF)

    p = parallel.Parallel()     # open LPT1
    time.sleep(0.01)
    p.setData(0x00)
    x=x+1
相关问题