Skip to main content
 首页 » 编程设计

python之Python中连续输入选择while循环

2024年09月07日8kerrycode

我在 Raspberry Pi 上使用 Python。 我想从距离传感器接收连续输入,并让距离值确定是否发送输出。

我有一个输出函数 gogo 和一个感测函数 sense,它更新距离值。

我希望在距离低于 20 时开始输出,在距离达到阈值 20 时停止输出,但我能看到的唯一解决方案是另一个循环。

我的代码不工作,我认为有一个很好的解决方案,但我不精通循环。

import RPi.GPIO as GPIO 
import time 
 
GPIO.setmode(GPIO.BCM) 
 
distance = 40.0 
 
TRIG = 4 
ECHO = 18 
 
GPIO.setup(TRIG,GPIO.OUT) 
GPIO.setup(ECHO,GPIO.IN) 
GPIO.setup(23, GPIO.OUT) 
GPIO.setup(24, GPIO.OUT) 
GPIO.setup(25, GPIO.OUT) 
 
def gogo():  
    Motor1A = 23 
    Motor1B = 24 
    Motor1E = 25 
 
    GPIO.setup(Motor1A,GPIO.OUT) 
    GPIO.setup(Motor1B,GPIO.OUT) 
    GPIO.setup(Motor1E,GPIO.OUT) 
 
    print "Turning motor on" 
    GPIO.output(Motor1A,GPIO.HIGH) 
    GPIO.output(Motor1B,GPIO.LOW) 
    GPIO.output(Motor1E,GPIO.HIGH) 
 
def sense(): 
    GPIO.output(TRIG, True) 
    time.sleep(0.00001) 
    GPIO.output(TRIG, False) 
 
    while GPIO.input(ECHO) == False: 
        start = time.time() 
 
    while GPIO.input(ECHO) == True: 
        end = time.time() 
 
    sig_time = end-start 
 
#CM: 
    distance = sig_time / 0.000058 
 
#inches: 
#distance = sig_time / 0.000148 
 
    print('Distance: {} centimeters'.format(distance)) 
 
while distance > 20.0: 
    print (distance) 
    sense() 
else: 
    print (distance) 
    gogo() 
    sense() 
 
GPIO.cleanup() 

请您参考如下方法:

问题是范围; distance 一直在您的 40 主代码中。它仅在 sense()

中更新

首先,让我们编辑sense来返回距离的值

def sense(): 
    GPIO.output(TRIG, True) 
    time.sleep(0.00001) 
    GPIO.output(TRIG, False) 
 
    while GPIO.input(ECHO) == False: 
        start = time.time() 
 
    while GPIO.input(ECHO) == True: 
        end = time.time() 
 
    sig_time = end-start 
 
#CM: 
    distance = sig_time / 0.000058 
 
#inches: 
#distance = sig_time / 0.000148 
 
    print('Distance: {} centimeters'.format(distance)) 
    return distance 

你或许还应该创建一个关闭电机的函数

你需要定义距离,让我们做一个永远运行的循环。现在,你的循环只运行到 distance< 20

distance = sense() 
while True: 
    if distance > 20: 
        <call motor off function here> 
        print (distance) 
    else: 
        print (distance) 
        gogo() 
    distance = sense() #now we're checking distance every cycle