Fields
Fields

Reputation: 21

python need faster response with getch

I'm trying to create a setup to blink a led and be able to control the frequency. Right now I'm just printing 10s as placeholders for testing. Everything runs and does what should, but getch is throwing me off.

freq = 1
while freq > 0:
    time.sleep(.5/freq) #half dutycycle / Hz
    print("1")
    time.sleep(.5/freq) #half dutycycle / Hz
    print("0")

    def kbfunc():
        return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
    #print(kbfunc())

    if kbfunc() == 27: #ESC
        break
    if kbfunc() == 49: #one
        freq = freq + 10
    if kbfunc() == 48: #zero
        freq = freq - 10

Now when it starts up, the freq change portion seems buggy like it's not reading all the time or I have to time the press just right. The break line has no problem whenever pressed though.

Upvotes: 0

Views: 230

Answers (2)

j2ko
j2ko

Reputation: 2539

from msvcrt import getch,kbhit
import time

def read_kb():
    return ord(getch()) if kbhit() else 0
def next_state(state):
    return (state + 1)%2 # 1 -> 0, 0 -> 1

freq = 1.0 # in blinks per second
state = 0
while freq > 0:
    print(state)
    state = next_state(state)

    key = read_kb()

    if key == 27: #ESC
        break
    if key == 49: #one
        freq = freq + 1.0
    if key == 48: #zero
        freq = max(freq - 1.0, 1.0)

    time.sleep(0.5/freq)

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96266

There should be only one kbfunc() call. Store the result in a variable.

E.g.: In your code if the key isn't Esc, you'll read the keyboard again.

Upvotes: 2

Related Questions