2017-01-23 111 views
0

我在Python中编写一些代码,以便在按下按钮时显示LCD信息。这是我的代码部分:在Python中暂停主线程

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_event_detect”为回调函数运行第二个线程,它不会暂停主线程。我希望按下按钮后,只要按下按钮,它就会保持在LCD上,然后从底部开始编码,在我的情况下是时间。 我该如何实现它?谢谢!

+1

您可以通过捕获按钮按下的时间并忽略按下按钮来快速“消除”它自己。这个问题的答案http://raspberrypi.stackexchange.com/questions/8544/gpio-interrupt-debounce可能会有所帮助。 –

+0

显示值切换有多快?你的按钮可能是弹跳。你可以阅读这个:https://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/robot/buttons_and_switches/ –

+0

也许你让我错了,或者我弄错了,但这里的问题不是重复的按钮按下。问题是我总是想要显示的代码是在while循环中,并且显示在主线程内的代码和由GPIO打开的另一个线程之间交替.add_event_detect – antonioag

回答

0

多线程充满了反直觉的惊喜。为了避免它们,我宁愿避免从两个不同的线程更新显示。

相反,我宁愿从处理程序线程发送消息,或者至少从中更新共享标志。

主循环将运行得更快,并在更新(草图)反应:

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 

免责声明:我没有测试此代码。

+0

感谢您的回答。无论如何,当GPIO.add_event_detect打开另一个进程时,我想暂停/中断主线程中的进程,以避免不同线程的双LCD更新。我无法得到它 – antonioag

+0

那么,更新信号处理程序线程中的“停止主线程”标志,休眠/检查主线程中的标志状态呢?但是,你不能在任意地方中断主线程,只是为了让它在特定的地方等待;多种合作多任务而不是先发制人。 – 9000