定时器只是第一次运行

时间:2015-04-23 22:12:26

标签: python python-3.x

首先,当谈到python时,我是一个完整的noobie。实际上,当我需要使用它时,我今天早上开始阅读它,如果代码是灾难,那就很抱歉。

我想完成这件事: 两个设备之间通过串行通信。运行python程序的设备必须监听由其他设备发送的一些数据并将其存储在文件中。但是每接收30秒的数据就必须向另一台设备发送命令,告诉它停止发送并开始扫描需要10秒钟。

这是我写过的代码。它不断打印打开连接..

    from serial import Serial
    from threading import Timer
    import time


    MOVE_TIME = 30.0
    SCAN_TIME = 10.0
    DEVICE_ADDRESS = '/dev/ttyACM0'
    BAUD_RATE = 9600

    while True:
        try:
            print("Opening connection...")
            ser = Serial(DEVICE_ADDRESS, BAUD_RATE
            break

        except SerialException:
            print("No device attached")


    def scan():
        print("Scanning...")
        timeout = time.time() + SCAN_TIME

        while True:
            #Some code I haven't thought of yet
            if time.time() > timeout:
                ser.write(b'r') #command to start
                break


    def send_stop_command():
        print("Sending stop command")
        ser.write(b's') #command to stop
        scan()

    t = Timer(MOVE_TIME + SCAN_TIME, send_stop_command)
    t.start()

    filename = time.strftime("%d-%m-%Y_%H:%M:%S") + ".txt"

    while True:
        data = ser.readline()
        try:
            with open(filename, "ab") as outfile:
                outfile.write(data)
                outfile.close()
        except IOError:
            print("Data could not be written")

0 个答案:

没有答案