Python中的暂停主线程
我正在用Python编写一些代码,这样当我按下按钮时,它就会在LCD显示屏上显示信息。这是我代码的一部分:Python中的暂停主线程,python,multithreading,gpio,Python,Multithreading,Gpio,我正在用Python编写一些代码,这样当我按下按钮时,它就会在LCD显示屏上显示信息。这是我代码的一部分: GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) def action1(self): temp = "15" lcd.clear() lcd.message(" Temp. Est.: \n" + " " + temp + " " + chr(223) + "C")
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def action1(self):
temp = "15"
lcd.clear()
lcd.message(" Temp. Est.: \n" + " " + temp + " " + chr(223) + "C")
time.sleep(5.0)
lcd.clear
GPIO.add_event_detect(18, GPIO.RISING,callback=action1, bouncetime=800)
while True:
date = datetime.now().strftime('%m-%d-%Y %H:%M')
lcd.message(date)
time.sleep(5.0)
lcd.clear()
此代码正在工作,但当我按下按钮时,它会显示温度,然后再次显示时间和温度(取决于我按下按钮的时间)。我已经读到“GPIO.add\u event\u detect”为回调函数运行第二个线程,它不会暂停主线程。我想,在按下按钮后,每当我按下按钮时,它都会停留在LCD上,然后它会从底部启动代码,在我的例子中是时间。
我怎样才能做到呢?谢谢大家! 多线程处理充满了违反直觉的惊喜。为了避免它们,我宁愿避免从两个不同的线程更新显示 相反,我宁愿从处理程序线程发送消息,或者至少从它更新一个共享标志 主循环将运行得更快,并对更新做出反应(草图):
免责声明:我没有测试此代码。您可以通过捕获按钮按下的时间并忽略随后过快的按钮按下来“消除”代码。这个问题的答案可能会有所帮助。显示值的切换速度有多快?你的按钮可能在弹跳。你可能会读到:也许你搞错了,或者我搞错了,但这里的问题不是反复按下按钮。问题是,我一直想显示的代码在while循环中,并且在主线程内的代码和GPIO打开的另一个线程之间交替显示。add\u event\u detect谢谢你的回答。无论如何,当GPIO打开另一个进程时,我想暂停/中断主线程中的进程。添加事件检测以避免不同线程的双LCD更新。我不能很好地得到它,更新信号处理程序线程中的“停止主线程”标志,然后在主线程中睡眠/检查标志状态?但是,您不能在任意位置中断主线程,而只是让它在特定位置等待;一种合作的多任务处理,而不是先发制人的。
desired_state = None # the shared flag, updated from key press handler.
current_state = 'show_date' # what we used to display
TICK = 0.1 # we check the state every 100 ms.
MAX_TICKS = 50 # we display a value for up to 5 seconds.
ticks_elapsed = 0
while True:
if desired_state != current_state:
# State changed, start displaying a new thing.
current_state = desired_state
ticks_elapsed = 0
if desired_state == 'show_date':
put_date_on_lcd()
elif desired_state == 'show_temp':
put_temp_on_lcd()
elif desired_state == 'blank':
clear_lcd()
else: # unknown state, we have an error in the program.
signal_error('What? %s' % desired_state)
# Advance the clock.
time.sleep(TICK)
ticks_elapsed += 1
if ticks_elapsed >= MAX_TICKS:
# Switch display to either date or blank.
desired_state = 'show_date' if current_state == 'blank' else 'blank'
ticks_elapsed = 0