代码调试,Raspberry pi中继和if语句

时间:2016-09-20 15:34:21

标签: python raspberry-pi

Raspberry Pi继电器存在问题。我之前写过关于LED的问题并且问题类似,但这次这些方法都不起作用。

#!/usr/bin/env python
import sys
import time
import datetime
import RPi.GPIO as GPIO
import SDL_DS1307

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

Rele1 = 17
Rele2 = 27



GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)

filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt"
starttime = datetime.datetime.utcnow()

ds1307 = SDL_DS1307.SDL_DS1307(1, 0x68)
ds1307.write_now()
while True:
        currenttime = datetime.datetime.utcnow()
        deltatime = currenttime - starttime
        data=time.strftime("%Y"+"%m"+"%d"+"%H"+"%M")
        with open('data.txt') as f:
                for line in f:
                        parts=line.split()
                        if parts[0]<=(data)<=parts[1]:
                                GPIO.output(Rele1, True)
                                GPIO.output(Rele2, False)
                                break
                        else:
                                GPIO.output(Rele1, False)
                                GPIO.output(Rele2, True)
        sleep(0.10)

我已经编辑了一点代码,现在就在ifTrue时,一个通道的继电器模块GPIO27点击非常快。我尝试更改GPIO但结果是一样的。

ifFalse时,继电器可以正常工作。如果我在break之后放置else,则代码会停止执行.txt文件检查,如果有更多日期,则程序不会执行任何操作

1 个答案:

答案 0 :(得分:0)

你需要对你的逻辑做一些工作。想想当data在第三行data.txt上的时间之间会发生什么。当您的代码读取第一行时,结果为false,因此输出相应地设置,然后在第二行结果为false,输出再次设置为false,然后第三行结果为true,因此输出设置为真的。然后立即再次读取文件,第一行结果为false,第二行为false,第三行为true。因此,每次读取文件时,您的继电器将被设置为false-false-true。

您需要使代码仅在任何测试为真(逻辑OR)时设置输出,而不是每次测试的结果。

你可能需要做一些事情,比如在文件的所有行之后计算OR,然后在完成文件后,如果结果为true或false,则相应地设置输出。

作为调试的提示,如果你在if语句的每个分支中放了一个简单的print语句,你会在控制台上看到,如果第一行之后的一行有一个真实的结果,输出就是每次通读文件时都会切换。

while True:
    currenttime = datetime.datetime.utcnow()
    deltatime = currenttime - starttime
    data=time.strftime("%Y"+"%m"+"%d"+"%H"+"%M")
    with open('data.txt') as f:
        result = False
        for line in f:
            parts=line.split()
            # compare the current time with the part1/part2 from data.txt
            if parts[0]<=(data)<=parts[1]:
                # The current time is between these, so our overall result is going to be True
                result = True
    # depending on the result, set the relays appropriately
    if result:
        print "Result is True"
        GPIO.output(Rele1, True)
        GPIO.output(Rele2, False)
    else:
        print "Result is False"
        GPIO.output(Rele1, False)
        GPIO.output(Rele2, True)
    # delay for a second - no point reading faster than the clock changes
    time.sleep(1)

`