1

I am writing code for an LCD screen using Python and I want it to display a flashing 'Press SELECT' message until a button on the LCD is pressed.

The problem is that while the program is in sleep, it does not register the user pressing the button, meaning that I have to press the button exactly when the message is being printed.

How can I do this without using sleep?

This is the code that I used:

#lcd.is_pressed(LCD.SELECT) - checks if button is pressed
#lcd.message - prints text on LCD
#lcd.clear - removes all text from LCD

while not lcd.is_pressed(LCD.SELECT):
      lcd.message ('Press Select')
      sleep(2)
      lcd.clear()
      sleep(2)
Wyetro
  • 8,439
  • 9
  • 46
  • 64
quelqu_un
  • 13
  • 2
  • you may have to measure the time that passes and decide to show/clear the message based on how much time has elapsed. – njzk2 Jan 21 '15 at 23:44
  • Can you use signals? It would be much easier to use an `alarm()` call with a handler, if they are available. – VHarisop Jan 21 '15 at 23:59

2 Answers2

0

Split your time into smaller slices; this checks the button every hundredth of a second:

i = 0
while not lcd.is_pressed(LCD.SELECT):
    i = (i + 1) % 400
    if i == 0:
        lcd.message("Press Select")
    elif i == 200:
        lcd.clear()
    sleep(0.01)
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
0

try this:

import time

delayTime=2 #In seconds
dummyVariable=is_pressed(LCD.Select)
while not dummyVariable:
    lcd.message('Press Select')
    dummyVariable=softWait(delayTime)
    lcd.clear()
    dummyVariable=softWait(delayTime)

def softWait(delayTime)
    t0 = time.time()
    t1 = time.time()
    while t0-t1<delayTime:
        dummyVariable=is_pressed(LCD.Select)
        t1=time.time()
        if dummyVariable:
            return True
    return False

Without knowing how is_pressed operates I can't really test this. But most likely problem is if is_pressed only registers True if the button is currently clicked where this would fail if the button click is faster than the time that it takes the system to return time.time() or lcd.message() calls. So really fast.

Canaryyellow
  • 157
  • 6