在python中,从函数外部停止并重新启动函数



我已经做了几天了,对这一切我都很陌生。我用的是树莓派4和sensehat。我想做的是在LED矩阵上显示几个不同的屏幕,我可以使用操纵杆在这些屏幕之间切换。问题是,其中一些将根据传感器数据进行更新,因此显示它们的功能尚未完成。这使得停止正在运行的功能和启动新功能变得困难。

到目前为止,我有这个:

from sense_hat import SenseHat
from gpiozero import CPUTemperature
import time
from multiprocessing import Process
sense = SenseHat()

def main_display():
w = (50, 50, 50)

display = [
w, w, w, w, w, w, w, w,
w, w, w, w, w, w, w, w,
w, w, w, w, w, w, w, w,
w, w, w, w, w, w, w, w,
w, w, w, w, w, w, w, w,
w, w, w, w, w, w, w, w,
w, w, w, w, w, w, w, w,
w, w, w, w, w, w, w, w
]

cpu_array = []
while True:
#attempt at calibrating temp for cpu temp
temp = sense.get_temperature()
cpu = CPUTemperature()
cpu_temp = cpu.temperature
if len(cpu_array) < 100:
cpu_array.append(cpu_temp)
else:
cpu_array.append(cpu_temp)
cpu_array.remove(cpu_array[0])
av_cpu_temp = sum(cpu_array) / len(cpu_array)
temp_calibrated = temp - ((av_cpu_temp - temp) * 1.6)

pres = sense.get_pressure()
hum = sense.get_humidity()
# temp column
temp_list = [56, 57, 48, 49, 40, 41, 32, 33, 24, 25, 16, 17, 8, 9, 0, 1]
temp_color = [(0, 0, 255), (20, 0, 235), (40, 0, 215), (70, 0, 185), (100, 0, 155), (120, 0, 135), (140, 0, 115), (160, 0, 95), (170, 0, 85), (180, 0, 75), (190, 0, 65), (200, 0, 55), (210, 0, 45), (220, 0, 35), (230, 0, 25), (255, 0, 0)]
i = 0
target_temp = 0
while i < len(temp_list):
if temp_calibrated >= target_temp:
display[temp_list[i]] = temp_color[i]
else:
display[temp_list[i]] = w
i += 1
target_temp += 3

# pres column    
pres_list = [59, 60, 51, 52, 43, 44, 35, 36, 27, 28, 19, 20, 11, 12, 3, 4]
pres_color = [(255,255,153), (255, 243, 157), (255,232,162), (255,209,172), (255, 197, 176), (255,185,181), (255,162,190), (255,139,199), (255,116,209), (255,93,218), (255, 81, 222), (255,70,227), (255,46,236), (255,23,246), (255, 11, 250), (255,0,255)]
j = 0
target_pres = 930
while j < len(pres_list):
if pres >= target_pres:
display[pres_list[j]] = pres_color[j]
else:
display[pres_list[j]] = w
j += 1
target_pres += 10

#hum column
hum_list = [62, 63, 54, 55, 46, 47, 38, 39, 30, 31, 22, 23, 14, 15, 6, 7]
hum_color = [(0,255,0), (0, 243, 11), (0,232,23), (0,209,46), (0,185,70), (0,162,93), (0, 150, 104), (0,139,116), (0,116,139), (0,93,162), (0, 81, 173), (0,70,185), (0,46,209), (0,23,232), (0, 11, 244), (0,0,255)]
k = 0
target_hum = 0
while k < len(hum_list):
if hum >= target_hum:
display[hum_list[k]] = hum_color[k]
else:
display[hum_list[k]] = w
k += 1
target_hum += 6.25

sense.set_pixels(display)
time.sleep(1)


p = Process(target=main_display)
p.start()
while True:
for event in sense.stick.get_events():
if event.action == "pressed":
if event.direction == "up":
p.start()
elif event.direction == "down":
p.terminate()
sense.clear()

它几乎可以工作,但当我试图在终止main_display函数后重新启动它时,我得到一个错误,一个函数只能启动一次。

您应该研究生成器和yield关键字。

本质上,它允许您放置某种断点并暂时退出函数。我相信你试图做的事情可以使用生成器来解决

最新更新