使用Python和pyparallel的方波

使用Python和pyparallel的方波,python,waveform,Python,Waveform,我想生成方时钟波形到外部设备 我在一台带有LPT1端口的旧PC上使用带Windows7 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) 我确实看到了方波(使用范围),但没有预期的时间周期 我将非常感激任

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

我在一台带有LPT1端口的旧PC上使用带Windows7 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)
我确实看到了方波(使用范围),但没有预期的时间周期


我将非常感激任何帮助

来产生这样的信号是很困难的。提到这很难的一个原因可能是,当超过睡眠时间时,进程会中断并返回

找到了这篇关于睡眠精确性的帖子,并给出了一个公认的答案:

另一个信息来源:

信息告诉您的是,Windows将能够进行至少10毫秒的睡眠,在Linux中,睡眠时间约为1毫秒,但可能会有所不同

更新 我制作了一个可以让睡眠时间少于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))
从时间导入时间,睡眠
导入时间信息
def定时器_睡眠(持续时间):
“”“timer_sleep()在给定的持续时间内睡眠(以秒为单位)。”
"""
停止时间=时间()+持续时间
当(时间()-停止时间)<0时:
#加入一些需要一点时间来处理的东西。
#根据评论中的测量结果,需要大约
#2使用秒来处理此问题。
睡眠(0)
如果名称=“\uuuuu main\uuuuuuuu”:
对于范围(1100)内的u_时间:
u_常数=1000000.0
持续时间=u_时间/u_常数
result=timeit.timeit(stmt='timer_sleep({time})').format(time=duration),
setup=“从\uuuuu主\uuuuuu导入计时器\u睡眠”,
数字=1)
打印('===运行#{nr}===='.格式(nr=u#u时间))
打印('在\t{time:.10f}秒后返回'。格式(time=result))
打印('应该花费\t{time:.10f}秒。格式(时间=持续时间))

Happy hacking

它提供了一段时间的预期性能。。。继续减少时间

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
并行导入
导入时间
x=0

虽然(X感谢您的回答。但无论如何,我需要与外部设备通信,我想我不是第一个,这意味着这是可能的。为了帮助您解决问题,您需要向我提供有关您使用的操作系统的更多信息。您阅读了我给您的链接吗?是的,我阅读了…我使用Windows 7 32位。波形行为怪异…当我使用大延迟时,它会停止,看起来像方波。我无法理解延迟和波形之间的相关性…没有延迟,我设置了类似2usec周期波形的东西…Sergey,想想当你切换par端口的输出一段时间时会发生什么。你指示系统将管脚设置为高,然后设置为低,多长时间大卫,它显然比较短,我试过了,但我认为它在不同的PC上会有所不同。不管怎样,它对我来说波形较慢。我想对于更快的波形,我需要连接到PC的CPLD/FPGA。这如何回答这个问题?用代码更新了我的答案,可以帮助你达到0.5ms