如何做比较值

How to do a comparison value

我使用(鼓角色)RaspPi 构建了这个自动化鱼菜共生系统 :) 并借此机会学习了如何使用 Python 进行编码。作为我的第一个项目,这是一个了不起的项目,但现在我已经达到了编码极限。我的种植床中有多个水传感器 HC-SR04,当我将水泵入其中时,传感器会测量距离。如果达到预设距离,则指示泵停止。

这很好用,但我的冗余大脑总是处于警报状态。如果传感器发生故障会怎样?然后泵仍在抽水,由于水损坏(这是一个室内项目 40 加仑水箱),我只好打电话给保险公司。

我该如何编写代码,以便在第一个达到以下值之一时泵停止?水位是距传感器 4 厘米还是抽水 2 分钟?

def Pumping_to_Growbed():
print ('')
print ('Pumping water to growbed')
time.sleep(1)
distance = Growbed_Sensor1_Measurement()
print ('Distance ', distance ,'cm')
while distance > 4:
   GPIO.output(RELAY_1, False)
   print ('distance ', distance ,'cm')
   distance = Growbed_Sensor1_Measurement() 
GPIO.output(RELAY_1, True) 
time.sleep(1) 

您想在 距离大于 4 且经过的时间小于 120 秒时循环。

你需要做的就是计算经过的时间,并将检查合并到while条件中:

start_t = time.time()

while distance > 4 and (time.time() - start_t < 120):
   ... 

然而,这假定循环将不断循环并且不会在某处被阻塞。如果您在循环中有潜在的长时间阻塞调用,这将不起作用。

如果你想在2分钟后停止。

def Pumping_to_Growbed():
    print ('')
    print ('Pumping water to growbed')
    time.sleep(1)
    distance = Growbed_Sensor1_Measurement()
    start = time()
    print ('Distance ', distance ,'cm')
    while distance > 4:
        GPIO.output(RELAY_1, False)
        print ('distance ', distance ,'cm')
        distance = Growbed_Sensor1_Measurement() 
        if time()-start >= 120:
            break
    GPIO.output(RELAY_1, True) 
    time.sleep(1)

这应该适用于 time() 与 sleep 在同一个包中的情况。