Simon De Roo
Simon De Roo

Reputation: 87

Intepreting held down keys

I am building a Raspberry Pi rover written in Python and I am looking to control the rover via SSH. Hence, I would run the script and then want the rover to move in the directions provided by me in real-time, like an RC car (think key up, key down, key left, key right).

I read online that one of the possibilities might be to use the pygame.key.get_pressed() function, but this is not working in my shell. When I run that command in my raspberry pi python shell, I only receive a tuple of zeros that times out after a fraction of a second.

My code is the following:

speed = input('How fast do you want the rover to go? Give a value lower than 1: ')

while True:
    keys = pygame.key.get_pressed()  #checking pressed keys
    if keys == True:
        if keys[pygame.K_UP]:
            fwd(speed)
        if keys[pygame.K_DOWN]:
            bwd(speed)
    if keys == False:
        MS.motor1off
        MS.motor2off     

with fwd and bwd being functions that activate the motors in the forward and backward directions.

When I run the script, it goes through the loop fine, but the motors do not respond to the key being held. When I added a print statement, I noticed that this was also not printed onto the console.

Does anyone have any idea how to proceed with this, please?

Upvotes: 2

Views: 189

Answers (3)

Nouman
Nouman

Reputation: 7313

From @WurzelseppQX's code , I have made a new code that prints a text as long as the button is kept pressed and will stop printing when the button is released. Here is the code:

import pygame  #importing pygame

pygame.init() #initializing pygame

width = 100 # width of window
height = 100 #height of window

pygame.display.set_mode((width, height)) # setting dimensions

while True:
    tbreak = False # to break two loops
    for event in pygame.event.get():   #getting events     
        if event.type == pygame.KEYDOWN: #see if a button is pressed
            if event.key == pygame.K_w: # if button is 'W' then
                while True: # making loop
                    print("Key 'W' pressed") 
                    ev = pygame.event.get() #getting events to see if the user just released the key
                    for e in ev: #looping the events
                        if e.type == pygame.KEYUP: #if any key is released
                            #You can also set specific keys
                            tbreak = True #to break the outerloop
                            break #breaking the inner loop
                    if tbreak == True:break #breaking

Now the above code blocks the rest of your game when the button is pressed. If you don't want your code to do this then use the following code:

global topass
topass = 0
def on_press(): #what to do on button press
    global topass
    print("Key 'W' pressed")
    topass = 1
while True:
    events = pygame.event.get()
    if len(events) == 0 and topass == 1:on_press()
    for event in events:
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w or topass == 1:
                on_press()
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_w:
                topass = 0

Upvotes: 0

skrx
skrx

Reputation: 20488

pygame.key.get_pressed() returns a list of booleans which represent the state of the keys. A list can never be equal to True or False so the code in your if keys == True: and if keys == False: clauses will never be executed.

So just get rid of these if clauses and use an else clause after if keys[pygame.K_UP]: or both statements to turn the motor off (not sure what exactly you want to do).

while True:
    # You must make a call to the event queue every frame or the window will "freeze".
    pygame.event.pump()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        fwd(speed)
    elif keys[pygame.K_DOWN]:
        bwd(speed)
    else:  # No key pressed.
        MS.motor1off
        MS.motor2off

By the way, if motor1off and motor2off are methods, you probably want to call them: MS.motor1off().

Upvotes: 2

WurzelseppQX
WurzelseppQX

Reputation: 540

I am not a pygame expert and have never used key.get_pressed() method. I use event.get() which works well. Here is a minimum example of the code I use:

import pygame

pygame.init()

WINDOW_WIDTH = 250
WINDOW_HEIGHT = 120

pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))

while True:
    for event in pygame.event.get():        
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                print('works!')

You must to make sure, that you initialize pygame and also create a window AND the window must be in the focus. Then it will work. If this is not convenient for you, then you have to hook into the keypress event of your keyboard so that you get the global keypress, no matter what window is in focus.

Hope this helps.

Upvotes: 2

Related Questions