I'm writing some code in Python so that it shows me info on LCD display when I press a button. 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. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.