为什么我的if语句只响应第一次测量?

时间:2017-09-20 14:43:49

标签: python

谢谢Whitebeard和其他所有人!现在正常运作。

我有一个功能可以测量为电容器充电所需的时间,然后在结束时输出该时间,这可以按预期工作。我有2个if语句,我需要在每个周期更新,但它们只对脚本的第一次测量做出反应。任何解释为什么这将是非常感谢。

import RPi.GPIO as GPIO, time
GPIO.setmode (GPIO.BOARD)

def RCtime(RCpin):
    reading = 0
    GPIO.setup (RCpin, GPIO.OUT)
    GPIO.output (RCpin, GPIO.LOW)
    time.sleep(.1)
    GPIO.setup (RCpin, GPIO.IN)
    while (GPIO.input(RCpin) == GPIO.LOW):
        reading += 1
    return reading
if RCtime <= 300000:
    relay1 = true
if RCtime > 300000:
    relay1 = false

while 1:
    print RCtime() #works as intended
    print relay1  #only works for the first cycle

到目前为止,这就是我的整个代码

为什么relay1在第一个循环中打印正确的true / false语句?
我不确定我的缩进在哪里出错了 在顶部初始化relay1 = None? 即使“print RCtime()”目前有效,我不应该将该函数用作变量吗?我应该怎样做一些不同的东西? 我非常感谢你的帮助。我试图抓住良好的基本面

2 个答案:

答案 0 :(得分:0)

您已命名一个与变量RCtime同名的函数RCtime

def Recalltime(RCpin):
    ....
    return reading

while True:
    RCtime = Recalltime()
    print RCtime
    if RCtime < 300000:
        relay1 = true
    if RCtime > 300000:
        relay1 = false

    print relay1

还有一个次要问题,因为当relay1完全等于RCtime时,行为未确定(30000未分配)。 (@Makoto在评论中提到)

答案 1 :(得分:0)

让它读取每个周期的if语句:

def RCtime(RCpin):
    ....
    return reading


while 1:
    rctime = RCtime(RCpin_value) #note assign function result to variable with different name
    print rctime
    if rctime < 300000: #might want this to be 'if rctime <= 300000' to avoid having no value in the case of rctime == 300000
        relay1 = True #in Python Boolean values are capitalized
    if rctime > 300000: #might want this to be an elif statement to eliminate need to call this test in the case first test is true
        relay1 = False
    print relay1