Search code examples
pythonpygamekeypress

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?


Solution

  • 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.