[英]Pause main thread in Python
I'm writing some code in Python so that it shows me info on LCD display when I press a button. 我正在用Python编写一些代码,以便当我按下按钮时可以在LCD显示屏上显示信息。 This is part of my code:
这是我的代码的一部分:
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()
This code is working but when I press the button it shows me the temperature, then the time and the temperature again (it depends on when I press the button). 该代码有效,但是当我按下按钮时,它会显示温度,时间和温度(取决于我何时按下按钮)。 I've read that "GPIO.add_event_detect" runs a second thread for callback functions and it does not pause the main thread.
我已经读到“ GPIO.add_event_detect”为回调函数运行第二个线程,并且它不会暂停主线程。 I would like that after the button is pressed it stays on the LCD whenever i push the button and then it starts the code from bottom, in my case with the time.
我希望在按下按钮后,只要我按一下按钮,它就会一直停留在LCD上,然后我会从下往上启动代码(以我的情况为准)。 How may I achieve it?
我该如何实现? Thank you!
谢谢!
Multithreading is full of counter-intuitive surprises. 多线程充满了违反直觉的意外。 To avoid them, I'd rather avoid updating the display from two different threads.
为了避免它们,我宁愿避免从两个不同的线程更新显示。
Instead, I'd rather send a message from the handler thread, or at least updated a shared flag from it. 相反,我宁愿从处理程序线程中发送一条消息,或者至少从中更新一个共享标志。
The main loop would run faster and react on the updates (a rough sketch): 主循环会运行得更快,并对更新做出反应(粗略的草图):
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
Disclaimer: I did not test this code. 免责声明:我没有测试此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.