在不断检查传感器输入的同时执行while循环

时间:2016-07-31 02:09:00

标签: python while-loop raspberry-pi sensor

我要做的是让我的RC响应用户击键然后相应地开车(前进,后退,左右转弯等)。但是,我还在前面安装了一个传感器。我想不断地测量那个读数,如果它低于一个阈值,它就会突破循环并且程序停止。我在不断阅读传感器方面遇到了麻烦。

当用户输入击键时,该程序目前只能获得1次读数。请帮忙

d1 = distance()

while (d1 >= 20):  
   d1 = distance()

   if (d1 <= 20):
      drive("stop")

   char = getch()

   if (char == "w"):
      drive("forward")

   char""

GPIO.cleanup()

1 个答案:

答案 0 :(得分:0)

如果distance()功能正常,它应该可以正常工作

d1 = distance()

while (d1 >= 20):  
   d1 = distance()

   char = getch()

   if (char == "w"):
      drive("forward")

   char = "" #maybe this typo ? 

drive("stop") #there is no need for overlaping logic in case of 20 

GPIO.cleanup()

您必须使用不同的方法

from threading import Thread
import time
dist = 0 

def distance(): # your function for messurment 
    global dist
    dist = #your messurment, ..

Thread(target = distance).start()

time.sleep(1) #give it time to do some readings

while(dist >= 20):
   char = getch()
   if(char == "w"):
      drive("forward")

drive("stop")
GPIO.cleanup()