python - 有没有一种方法可以使函数连续运行,直到用户告诉它停止?
问题描述
我目前正在尝试在 Python 3 中为树莓派编写一个程序,以控制位于桌子上的一组线性致动器,这将改变腿的长度并允许桌面倾斜。桌子的一个特点是自动调平功能,以确保桌面始终保持水平,并且如果它检测到它不是通过从板载加速器中提取数据,它将自我纠正。自动级别功能工作得非常好,但是我在编程开和关条件时遇到了困难。理想情况下,在控制台中键入 a(1) 将调用 autolevel 函数并使其持续运行,直到键入 a(0) 停止它。我设法通过键入 a(1) 来运行该函数,但是一旦接受该命令,程序就会停止侦听进一步的命令并无休止地循环。
def a(n):
while n== 1:
acceleration = sense.get_accelerometer_raw()
x = acceleration['x']
y = acceleration['y']
z = acceleration['z']
x=round(x, 3)
y=round(y, 3)
z=round(z, 3)
if x >0.00:
GPIO.output(12,0)
GPIO.output(13,1)#leg 1 retract
GPIO.output(15,0)
GPIO.output(29,1)#leg 2 retract
GPIO.output(31,1)
GPIO.output(32,0)#leg 3 extend
GPIO.output(33,1)
GPIO.output(36,0)#leg 4 extend
sense.show_message('Correcting forward tilt')
elif x <0.00:
GPIO.output(12,1)
GPIO.output(13,0)#leg 1 extend
GPIO.output(15,1)
GPIO.output(29,0)#leg 2 extend
GPIO.output(31,0)
GPIO.output(32,1)#leg 3 retract
GPIO.output(33,0)
GPIO.output(36,1)#leg 4 retract
sense.show_message('Correcting rearward tilt')
else:
if y >0.00:
GPIO.output(12,0)
GPIO.output(13,1)#leg 1 retract
GPIO.output(15,1)
GPIO.output(29,0)#leg 2 extend
GPIO.output(31,0)
GPIO.output(32,1)#leg 3 retract
GPIO.output(33,1)
GPIO.output(36,0)#leg 4 extend
sense.show_message('Correcting right side tilt')
elif y <0.00:
GPIO.output(12,1)
GPIO.output(13,0)#leg 1 extend
GPIO.output(15,0)
GPIO.output(29,1)#leg 2 retract
GPIO.output(31,1)
GPIO.output(32,0)#leg 3 extend
GPIO.output(33,0)
GPIO.output(36,1)#leg 4 retract
sense.show_message('Correcting left side tilt')
else:
sense.show_message("No tilt to correct")
print ("Stand currently level, standing by for reactive adjustment.")
解决方案
您可以使用多线程,以下是如何将其合并到:
您将被要求输入值,在您的情况下将是“退出”关键字。让我知道是否有效。
import threading
flag=False
def a1():
global flag
a= flag
#if(a==True):
while (!a):
acceleration = sense.get_accelerometer_raw()
x = acceleration['x']
y = acceleration['y']
z = acceleration['z']
#paste the rest of your code here
def loopBreak():
"""
function to exit the loop
"""
global flag
inp=input("Enter value")
if inp=="exit":
flag =True
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=a1)
t2 = threading.Thread(target=loopBreak)
# starting thread 1
t1.start()
# starting thread 2
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
print(flag)
# both threads completely executed
print("Done!")
推荐阅读
- android - 数据绑定 - 错误:找不到符号变量
- bash - 编写一个 shell 脚本来替换文件中的电话号码
- javascript - 如何将 Js 中的函数从逗号更改为点
- javascript - javascript中方法内部的未定义属性
- android - 模拟器对windows图形驱动的依赖
- android - 如何水平排列三个视图?
- ios - 使用 URL 显示 Facebook 用户图片 (Swift 5 | Xcode 10)
- html - 如何在 ionic 4 中使用 css 将时间线居中
- python - 使用列表推导创建使用 dict 值放在一起的字符串列表
- python - 如何通过命令提示符运行多个 python 文件